C++ supports several unary operators, each serving a unique purpose in manipulating the variables. Let’s start with the increment and decrement operators which are commonly used in loops and various algorithms.
Example 1: Increment (++) and Decrement (–) Operators
The increment (++) and decrement (–) unary operators are fundamental tools in C++ for modifying the value of a variable by either increasing or decreasing it by 1, respectively. The increment operator (++) adds 1 to the variable’s value, while the decrement operator (–) subtracts 1. These operators can be applied to integer, floating-point, and pointer variables, providing flexibility in their usage.
Let’s explore these operators through a practical example:
using namespace std;
int main()
{
int counter = 0;
// Increment operator
cout << "Initial value: " << counter << endl;
counter++;
cout << "Value after increment: " << counter << endl;
// Decrement operator
counter--;
cout << "Value after decrement: " << counter << endl;
return 0;
}
This simple C++ program includes the necessary input/output stream library with “#include <iostream>”. Within the “main()” function, we instantiate an integer variable called “counter” and assign it with an initial value of 0. Using the “cout” statement, we print the initial value of the “counter” to the console, providing a baseline for our demonstration. Moving forward, the increment operator (counter++) is utilized to raise the “counter” variable value by 1.
After this operation, the updated value of “counter” is displayed using another “cout” statement. Subsequently, we utilize the decrement operator (counter—) to decrease the value of “counter” by 1. The outcome is subsequently displayed on the console. Ultimately, the program concludes with the “return 0;” statement which indicates a successful execution.
The output image shows the initial value, the value after the increment, and the decremented value.
Example 2: Positive (+) and Negative (-) Operators
While the positive unary operator is rarely used, the negative operator is fundamental for changing the sign of a variable.
Using namespace std;
int main() {
int positiveValue = 10;
int negativeValue = -positiveValue;
cout << "Positive value: " << positiveValue << endl;
cout << "Negative value: " << negativeValue << endl;
return 0;
}
We initialize two integer variables for this example code which are “positiveValue” and “negativeValue”. The “positiveValue” is assigned with the value of 10. Subsequently, we declare the “negativeValue” and assign it with the negation of “positiveValue” using the unary minus operator. This operator effectively changes the sign of the original value. We then utilize the “cout” statement to display both the positive as well as the negative output on the console. Finally, the program returns 0 which indicates the successful completion of the main function.
When executed, this program outputs the positive and negative values.
Example 3: Logical NOT (!) Operator
The unary operator in C++, denoted by the “!” symbol, is known as the logical NOT operator. It is designed to invert the truth value of a given expression. It operates on a single operand which is typically a logical expression or a condition. The logical NOT operation yields a “true” outcome when the operand is “false” and yields a “false” outcome when the operand is “true”.
Here’s a simple example that demonstrates the usage of the logical NOT operator:
using namespace std;
int main() {
bool isTrue = true;
bool isFalse = false;
bool resultNotTrue = !isTrue;
bool resultNotFalse = !isFalse;
cout << "Original Value: " << isTrue << ", After NOT: " << resultNotTrue << endl;
cout << "Original Value: " << isFalse << ", After NOT: " << resultNotFalse << endl;
return 0;
}
In this example, we declare two Boolean variables, “isTrue” and “isFalse”. We then apply the logical NOT operator to each variable, storing the results in “resultNotTrue” and “resultNotFalse”, respectively. The program subsequently prints the original values and the results of the logical NOT operation for both variables.
Upon executing this program, we will notice that the logical NOT operator reverses the truth value of “isTrue” (initially set to true), rendering it false. Similarly, it inverts the truth value of “isFalse” (originally false), yielding true.
The output clearly illustrates the inversion of the truth values that are achieved by the logical NOT operator.
Example 4: Bitwise NOT (~) Operator
The bitwise NOT operator (~) in C++ is a unary operator that performs the bitwise negation of each bit of its operand. It functions with fundamental data types, specifically integral ones, such as integers. The outcome is achieved by inverting every individual bit in the operand, converting 0s to 1s and 1s to 0s.
To illustrate its usage, consider the following code snippet:
using namespace std;
int main() {
int originalValue = 5;
int resultBitwiseNot = ~originalValue;
cout << "Original Value: " << originalValue << ", After Bitwise NOT: " << resultBitwiseNot << endl;
return 0;
}
In this example, we declare an “originalValue” integer variable with the value of “5”. Next, we utilize the bitwise NOT operator (~) on this variable. The result of this variable is stored in “resultBitwiseNot”. The program then prints the original value and the result after the bitwise NOT operation by utilizing the “cout” statement.
When we run this program, we'll see that the bitwise NOT operator inverts each bit of the binary representation of “originalValue”, resulting in a new value.
Example 5: Address and Indirection Operators
The address-of operator, denoted by the “&” symbol, serves the purpose of retrieving the memory location of a variable. It returns a pointer to the variable which enables an indirect access to its value. The indirection or dereference operator (*) obtains the value that is stored at the memory location that is specified by a pointer. It provides a way to work with the actual data through a pointer indirectly.
Let’s comprehend the concept with an example:
using namespace std;
int main() {
int value = 99;
cout << "Original Value: " << value << endl;
int* ptr = &value;
cout << "Memory Address: " << ptr << endl;
int retrievedValue = *ptr;
cout << "Retrieved Value: " << retrievedValue << endl;
return 0;
}
This code exemplifies the utilization of address and indirection operators. First, an integer variable named “value” is initialized with the value of 99. The original value of “value” is then outputted to the console. Subsequently, a “ptr” pointer variable is declared, and the address-of operator (&) is employed to assign the memory address of “value” to “ptr”. The program then outputs this memory address, showcasing the basic operation of the “address” operator.
After that, a new integer variable which is “retrievedValue” is declared, and the indirection operator (*) is employed to retrieve the value that is stored at the memory address pointed by “ptr”. The retrieved value is then outputted to the console.
Conclusion
This article provided a comprehensive exploration of unary operators in C++. We began by categorizing the unary operators into various types including arithmetic, logical, bitwise, and those related to address and indirection. Real-world situations were exemplified to demonstrate the useful application of these operators. These operators play pivotal roles in C++ programming which allows the developers to work with pointers efficiently and manage the memory.