Unary Operators
suggest changeUnary operators act on the object upon which they are called and have high precedence.
When used postfix, the action occurs only after the entire operation is evaluated, leading to some interesting arithmetic:
int a = 1;
++a; // result: 2
a--; // result: 1
int minusa=-a; // result: -1
bool b = true;
!b; // result: false
a=4;
int c = a++/2; // 4 / 2, result 2; a is then 5
std::cout << a << std::endl; // prints 5
int d = ++a/2; // a becomes 6, then 6 / 2; result 3
int arr[4] = {1,2,3,4};
int *ptr1 = &arr[0]; // points to arr[0] which is 1
int *ptr2 = ptr1++; // ptr2 points to arr[0] which is still 1; ptr1 incremented
std::cout << *ptr1++ << std::endl; // prints 2
int e = arr[0]++; // receives the value of arr[0] before it is incremented
std::cout << e << std::endl; // prints 1
std::cout << *ptr2 << std::endl; // prints arr[0] which is now 2
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents