Would you know, categorically, what the variable x
will contain?
x = 3 * 2 < 4;
The question raised here is which operator will be executed first: multiplication or comparison? There is a table of operator precedence shown below. You can see that multiplication (precedence 3) has priority over comparison (prcedence 6):
Precedence | Operators | Description | Associativity |
---|---|---|---|
1 | ++ -- |
Pre-increment and pre-decrement | ![]() |
2 | ! ~ + - |
Unary operators | ![]() |
3 | * / % |
Multiplication, division and modulo | ![]() |
4 | + - |
Addition and subtraction | ![]() |
5 | << >> |
Bit shifting | ![]() |
6 | < > <= >= |
Comparison operators | ![]() |
7 | == != |
Equality operators | ![]() |
8 | & |
Logical bitwise AND | ![]() |
9 | ^ |
Exclusive bitwise OR | ![]() |
10 | | |
Inclusive bitwise OR | ![]() |
11 | && |
Logical ANBD | ![]() |
12 | || |
Logical OR | ![]() |
13 | = != += *= &= etc |
Assignment operators | ![]() |
14 | ++ -- |
Post-increment and post-decrement | ![]() |
Would you be able, now, to give with certainty the value of x
after these lines of code?
int a=5, x;
x = a = 3;
In this example, the =
operator appears twice in the same instruction. Of course,
both operators have the same precedence. But fortunately, for each operator is defined
an associativity. It is this associativity that determines the order of operators of the same precedence.
In the last column of the precedence table we see that the associativity
is defined from the right to the left for the =
operator. The equivalent instructions are therefore :
int a=5, x;
a = 3;
x = a;
Obviously, no one knows the priority table by heart. The easiest way, if you are doubt, is to add parentheses to impose the order of execution of the of the different operators. This also makes it easier for other developers to u nderstand your code if they have to analyze it. Just remember that the multiplication and division operators have priority over over addition and subtraction.
Write a program that calculates the value of x (eliminate unnecessary brackets):
$$ x = \dfrac{125,5+12,5}{5468,12} - 12,5*2,54 $$
The result of the calculation should be -31.724763.
Will a precedence 1 operator be executed after a precedence 2 operator?
When does associativity apply?
How to write this instruction to make it easier to understand.
x = c > a * b;
How to write this instruction to make it easier to understand.
x = 3 * 2 && 0;
x
will always be equal to 0 because the last operation is always && 0
.
Try again...
What will be the value of the variable x
after these lines?
int a=3, x;
x = a += 5;
+=
is executed first because associativity is from right to left.
Try again...
What will be the value of the variable x
after these lines?
int a=3, x;
x = a == 5;
==
is executed first and comparison will always return 0.
Try again...
What will be the value of the variable x
after these lines?
int a=-3;
x = 0<a<20;
What will be the value of the variable x
after these lines?
int a=-3;
x = 0<a && a<20;