Compound Assignment Operators In C
Now we know how to use variables and constants, we can begin to use them with operators. Operators are integrated in the C++ language. The C++ operators are mostly made out of signs (some language use keywords instead.)
Assignment
We used this operator before and it should already be known to you. For the people that didn’t read the previous tutorials we will give a short description.
With an assignment (=) operator you can assign a value to a variable.
For example: A = 5; or B = -10; or A = B;
Let’s look at A = B : The value that is stored in B will be stored in A. The initial value of A will be lost.
So if we say:
Then A will contain the value twenty.
The following expression is also valid in C++: A = B = C = 10;
The variables A,B,C will now contain the value ten.
Calculations (arithmetic operators)
There are different operators that can be used for calculations which are listed in the following table:
Operator | Operation |
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus(Remainder |
Now that we know the different operators, let’s calculate something:
Note: The value stored in A at the end of the program will be eight.
Compound assignments
Compound assignments can be used when you want to modify the value of a variable by performing an operation on the value currently stored in that variable. (For example: A = A + 1 ).
- Writing <var> += <expr> is the same as <var> = <var> + <expr>.
- Writing <var> -= <expr> is the same as <var> = <var> – <expr>.
- Writing <var> /= <expr> is the same as <var> = <var> / <expr>.
- Writing <var> *= <expr> is the same as <var> = <var> * <expr>.
Decrease and increase operators
The increase operator (++) and the decrease operator (–) are used to increase or reduce the value
stored in the variable by one.
Example: A++; is the same as A+=1; or A= A + 1;
A characteristic of this operator is that it can be used as a prefix or as a suffix (before or after). Example: A++; or ++A; have exactly the same meaning. But in some expressions they can have a different result.
For instance: In the case that the decrease operator is used as a prefix (–A) the value is decreased before the result of the expression is evaluated. Example:
Note:My_var is decreased before the value is copied to A. So My_var contains 9 and A will contain 9.
In case that it is used as a suffix (A–) the value stored in A is decreased after being evaluated and therefore the value stored before the decrease operation is evaluated in the outer expression. Example:
Note:The value of My_var is copied to A and then My_var is decreased. So My_var will contain 9 and A will contain 10.
Relation or equal operators
With the relation and equal operators it is possible to make a comparison between two expressions. The result is a Boolean value that can be true or false. See the table for the operators:
== | Equal |
!= | Not equal |
> | Greater |
< | Less |
>= | Greater than or equal to |
<= | Less than or equal to |
You have to be careful that you don’t use one equal sign (=) instead of two equal signs (==). The first one is an assignment operator, the second one is a compare operator.
Logical operators
Logical operators are mainly used to control program flow. Usually, you will find them as part of an if, while, or some other control statement. The operators are:
- <op1> || <op2> – A logical OR of the two operands
- <op1> && <op2> – A logical AND of the two operands
- ! <op1> – A logical NOT of the operand.
Logical operands allow a program to make decisions based on multiple conditions. Each operand is considered a condition that can be evaluated to a true or false value. Then the value of the conditions is used to determine the overall value of the statement. Take a look at the tables below:
Table: && operator (AND)
<op1> | <op2> | <op1> && <op2> |
true | true | true |
true | false | false |
false | true | false |
false | false | false |
Table: || operator (OR)
<op1> | <op2> | <op1> || <op2> |
true | true | true |
true | false | true |
false | true | true |
false | false | false |
Some examples:
Bitwise operators
The bitwise operators are similar to the logical operators, except that they work with bit patterns. Bitwise operators are used to change individual bits in an operand.
operator | asm equivalent | description |
& | AND | Bitwise |
| | OR | Bitwise |
^ | XOR | Bitwise |
~ | NOT | Unary |
<< | SHL | Shift |
>> | SHR | Shift |
That is all for this tutorial.
HACKED BY SudoX — HACK A NICE DAY.
Operators
Once introduced to variables and constants, we can begin to operate with them by using operators. What follows is a complete list of operators. At this point, it is likely not necessary to know all of them, but they are all listed here to also serve as reference.Assignment operator (=)
The assignment operator assigns a value to a variable.This statement assigns the integer value to the variable . The assignment operation always takes place from right to left, and never the other way around:
This statement assigns to variable the value contained in variable . The value of at the moment this statement is executed is lost and replaced by the value of .
Consider also that we are only assigning the value of to at the moment of the assignment operation. Therefore, if changes at a later moment, it will not affect the new value taken by .
For example, let's have a look at the following code - I have included the evolution of the content stored in the variables as comments:
This program prints on screen the final values of and (4 and 7, respectively). Notice how was not affected by the final modification of , even though we declared earlier.
Assignment operations are expressions that can be evaluated. That means that the assignment itself has a value, and -for fundamental types- this value is the one assigned in the operation. For example:
In this expression, is assigned the result of adding 2 and the value of another assignment expression (which has itself a value of 5). It is roughly equivalent to:
With the final result of assigning 7 to .
The following expression is also valid in C++:
It assigns 5 to the all three variables: , and ; always from right-to-left.
Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by C++ are:operator | description |
---|---|
addition | |
subtraction | |
multiplication | |
division | |
modulo |
Operations of addition, subtraction, multiplication and division correspond literally to their respective mathematical operators. The last one, modulo operator, represented by a percentage sign (), gives the remainder of a division of two values. For example:
results in variable containing the value 2, since dividing 11 by 3 results in 3, with a remainder of 2.
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Compound assignment operators modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand:expression | equivalent to... |
---|---|
and the same for all other compound assignment operators. For example:
Increment and decrement (++, --)
Some expression can be shortened even more: the increase operator () and the decrease operator () increase or reduce by one the value stored in a variable. They are equivalent to and to , respectively. Thus:are all equivalent in its functionality; the three of them increase by one the value of .
In the early C compilers, the three previous expressions may have produced different executable code depending on which one was used. Nowadays, this type of code optimization is generally performed automatically by the compiler, thus the three expressions should produce exactly the same executable code.
A peculiarity of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable name () or after it (). Although in simple expressions like or , both have exactly the same meaning; in other expressions in which the result of the increment or decrement operation is evaluated, they may have an important difference in their meaning: In the case that the increase operator is used as a prefix () of the value, the expression evaluates to the final value of , once it is already increased. On the other hand, in case that it is used as a suffix (), the value is also increased, but the expression evaluates to the value that x had before being increased. Notice the difference:
Example 1 | Example 2 |
---|---|
In Example 1, the value assigned to is the value of after being increased. While in Example 2, it is the value had before being increased.
Relational and comparison operators ( ==, !=, >, <, >=, <= )
Two expressions can be compared using relational and equality operators. For example, to know if two values are equal or if one is greater than the other.The result of such an operation is either true or false (i.e., a Boolean value).
The relational operators in C++ are:
operator | description |
---|---|
Equal to | |
Not equal to | |
Less than | |
Greater than | |
Less than or equal to | |
Greater than or equal to |
Here there are some examples:
Of course, it's not just numeric constants that can be compared, but just any value, including, of course, variables. Suppose that , and , then:
Be careful! The assignment operator (operator , with one equal sign) is not the same as the equality comparison operator (operator , with two equal signs); the first one () assigns the value on the right-hand to the variable on its left, while the other () compares whether the values on both sides of the operator are equal. Therefore, in the last expression (), we first assigned the value to and then we compared it to (that also stores the value 2), yielding .
Logical operators ( !, &&, || )
The operator is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing if its operand is , and if its operand is . Basically, it returns the opposite Boolean value of evaluating its operand. For example:The logical operators and are used when evaluating two expressions to obtain a single relational result. The operator corresponds to the Boolean logical operation AND, which yields if both its operands are , and otherwise. The following panel shows the result of operator evaluating the expression :
&& OPERATOR (and) |
---|
The operator corresponds to the Boolean logical operation OR, which yields if either of its operands is , thus being false only when both operands are false. Here are the possible results of :
|| OPERATOR (or) |
---|
For example:
When using the logical operators, C++ only evaluates what is necessary from left to right to come up with the combined relational result, ignoring the rest. Therefore, in the last example (), C++ evaluates first whether is , and if so, it never checks whether is or not. This is known as short-circuit evaluation, and works like this for these operators:
operator | short-circuit |
---|---|
if the left-hand side expression is , the combined result is (the right-hand side expression is never evaluated). | |
if the left-hand side expression is , the combined result is (the right-hand side expression is never evaluated). |
This is mostly important when the right-hand expression has side effects, such as altering values:
Here, the combined conditional expression would increase by one, but only if the condition on the left of is , because otherwise, the condition on the right-hand side () is never evaluated.
Conditional ternary operator ( ? )
The conditional operator evaluates an expression, returning one value if that expression evaluates to , and a different one if the expression evaluates as . Its syntax is:If is , the entire expression evaluates to , and otherwise to .
For example:
In this example, was 2, and was 7, so the expression being evaluated () was not , thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was (with a value of 7).
Comma operator ( , )
The comma operator () is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.For example, the following code:
would first assign the value 3 to , and then assign to variable . So, at the end, variable would contain the value 5 while variable would contain value 3.
Bitwise operators ( &, |, ^, ~, <<, >> )
Bitwise operators modify variables considering the bit patterns that represent the values they store.operator | asm equivalent | description |
---|---|---|
Bitwise AND | ||
Bitwise inclusive OR | ||
Bitwise exclusive OR | ||
Unary complement (bit inversion) | ||
Shift bits left | ||
Shift bits right |
Explicit type casting operator
Type casting operators allow to convert a value of a given type to another type. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):The previous code converts the floating-point number to an integer value (); the remainder is lost. Here, the typecasting operator was . Another way to do the same thing in C++ is to use the functional notation preceding the expression to be converted by the type and enclosing the expression between parentheses:
Both ways of casting types are valid in C++.
sizeof
This operator accepts one parameter, which can be either a type or a variable, and returns the size in bytes of that type or object:Here, is assigned the value , because is a type with a size of one byte.
The value returned by is a compile-time constant, so it is always determined before program execution.
Other operators
Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the specifics for object-oriented programming.Precedence of operators
A single expression may have multiple operators. For example:In C++, the above expression always assigns 6 to variable , because the operator has a higher precedence than the operator, and is always evaluated before. Parts of the expressions can be enclosed in parenthesis to override this precedence order, or to make explicitly clear the intended effect. Notice the difference:
From greatest to smallest priority, C++ operators are evaluated in the following order:
Level | Precedence group | Operator | Description | Grouping |
---|---|---|---|---|
1 | Scope | scope qualifier | Left-to-right | |
2 | Postfix (unary) | postfix increment / decrement | Left-to-right | |
functional forms | ||||
subscript | ||||
member access | ||||
3 | Prefix (unary) | prefix increment / decrement | Right-to-left | |
bitwise NOT / logical NOT | ||||
unary prefix | ||||
reference / dereference | ||||
allocation / deallocation | ||||
parameter pack | ||||
C-style type-casting | ||||
4 | Pointer-to-member | access pointer | Left-to-right | |
5 | Arithmetic: scaling | multiply, divide, modulo | Left-to-right | |
6 | Arithmetic: addition | addition, subtraction | Left-to-right | |
7 | Bitwise shift | shift left, shift right | Left-to-right | |
8 | Relational | comparison operators | Left-to-right | |
9 | Equality | equality / inequality | Left-to-right | |
10 | And | bitwise AND | Left-to-right | |
11 | Exclusive or | bitwise XOR | Left-to-right | |
12 | Inclusive or | bitwise OR | Left-to-right | |
13 | Conjunction | logical AND | Left-to-right | |
14 | Disjunction | logical OR | Left-to-right | |
15 | Assignment-level expressions | assignment / compound assignment | Right-to-left | |
conditional operator | ||||
16 | Sequencing | comma separator | Left-to-right |
When an expression has two operators with the same precedence level, grouping determines which one is evaluated first: either left-to-right or right-to-left.
Enclosing all sub-statements in parentheses (even those unnecessary because of their precedence) improves code readability.
0 thoughts on “Compound Assignment Operators In C”
-->