β C++ Unary Operators β Operate on a Single Operand
π§² Introduction β What Are Unary Operators in C++?
Unary operators in C++ operate on a single operand to perform operations such as incrementing, decrementing, negating, or logical testing. These operators are essential for loop control, logical expressions, pointer manipulation, and mathematical transformations.
π― In this guide, youβll learn:
- The list and function of unary operators
- Pre- and post-increment/decrement usage
- Logical and address-related operators
- Common use cases and coding tips
π List of C++ Unary Operators
Operator | Symbol | Description | Example |
---|---|---|---|
Unary plus | + | Returns the positive value (identity) | +a |
Unary minus | - | Negates the value | -a |
Logical NOT | ! | Inverts a boolean value | !flag |
Bitwise NOT | ~ | Inverts all bits | ~x |
Pre-increment | ++a | Increments value before use | ++i |
Post-increment | a++ | Increments value after use | i++ |
Pre-decrement | --a | Decrements value before use | --i |
Post-decrement | a-- | Decrements value after use | i-- |
Address-of | & | Returns the memory address | &x |
Dereference | * | Accesses value at a pointer | *ptr |
βοΈ Example β Pre vs Post Increment
int x = 5;
int a = ++x; // x becomes 6, a = 6
int b = x++; // b = 6, x becomes 7
π§ Logical NOT !
bool flag = false;
cout << !flag; // Outputs 1 (true)
π§ Bitwise NOT ~
int a = 5; // 00000101
int b = ~a; // 11111010 (Two's complement of 6)
π¦ Address-of &
and Dereference *
These are pointer-related unary operators:
int x = 100;
int* ptr = &x; // Address-of
cout << *ptr; // Dereference β outputs 100
β οΈ Common Mistakes
β Mistake | β Fix |
---|---|
Confusing pre and post ops | Know when value changes vs when itβs returned |
Dereferencing uninitialized pointers | Always assign valid address to pointer |
Using ~ on float/double | Only use ~ on integers |
Applying & on temporary values | Use & on actual variables, not rvalues |
π Summary β Recap & Next Steps
π Key Takeaways:
- Unary operators work with a single operand
- Pre/post increment/decrement behave differently in expressions
- Logical and bitwise NOT serve distinct purposes
*
and&
are critical in pointer operations
βοΈ Real-World Relevance:
Unary operators are used in looping constructs, bitmasking, boolean logic, and pointer dereferencing, making them fundamental to efficient and effective C++ coding.
β FAQs β C++ Unary Operators
β What is the difference between ++i
and i++
?
β
++i
increments before using the value; i++
increments after using it.
β Can I use ++
with float or double?
β
Yes. All numeric types support ++
and --
.
β What does ~
do to a number?
β
It flips all the bits (bitwise complement), resulting in -n - 1
.
β Are &
and *
also unary operators?
β
Yes. &
returns an address, *
accesses the value at an address.
β Can I chain unary operators?
β
Yes. Example: --*ptr
decrements the value pointed to by ptr
.
Share Now :