Prefix and Postfix & Compound assignment
Prefix and postfix operators in C++
Prefix and postfix operators are used to modify the value of a variable. The prefix operator is used before the variable, while the postfix operator is used after the variable.
The following table shows some of the most common prefix and postfix operators in C++:
Operator | Prefix | Postfix |
---|---|---|
++ | Increments the value of the variable by 1. | Increments the value of the variable by 1, and returns the original value. |
— | Decrements the value of the variable by 1. | Decrements the value of the variable by 1, and returns the original value. |
Example
The following code shows how to use the prefix and postfix operators to increment the value of a variable:
int a = 10; // Increment the value of a by 1 using the prefix operator. a++; // Increment the value of a by 1 using the postfix operator. int b = a++ // Print the values of a and b. std::cout << a << " " << b << std::endl;
Output:
12 11
Compound assignment operators in C++
Compound assignment operators combine arithmetic operations with assignment operations. This makes it possible to modify the value of a variable in a single statement.
The following table shows some of the most common compound assignment operators in C++:
Operator | Description | Example |
---|---|---|
+= |
Adds the operand to the left operand | x += 5; is equivalent to x = x + 5; |
-= |
Subtracts the operand from the left operand | y -= 3; is equivalent to y = y - 3; |
*= |
Multiplies the operand with the left operand | z *= 2; is equivalent to z = z * 2; |
/= |
Divides the left operand by the operand | a /= 4; is equivalent to a = a / 4; |
%= |
Computes the modulo of the left operand and the operand | b %= 7; is equivalent to b = b % 7; |
&= |
Performs a bitwise AND operation on the left operand and the operand | c &= 6; is equivalent to c = c & 6; |
^= |
Performs a bitwise XOR operation on the left operand and the operand | e ^= 8; is equivalent to e = e ^ 8; |
<<= |
Shifts the left operand left by the number of bits specified by the operand | f <<= 3; is equivalent to f = f << 3; |
>>= |
Shifts the left operand right by the number of bits specified by the operand | g >>= 2; is equivalent to g = g >> 2; |
Example
The following code shows how to use compound assignment operators to modify the value of a variable:
int a = 10; // Increment the value of a by 1 using the compound assignment operator. a += 1; // Print the value of a. std::cout << a << std::endl;
Output:
11
Compound assignment operators can be a powerful tool for writing concise and efficient C++ code.