int i = 2*5/2;
int j = 2*(5/2);
printf("%dn,%dn",i,j);
Variable Associativity: when I run this program, the first statement gives me i = 4;
Shouldn’t it give me 2, because according to BODMAS rule /
is evaluated before *
, so the variable should have been evaluated as (5/2)=2
and then 2*2=4
?
I know this is a noob question, but this never fails to surprise me.
1
The BODMAS rule is misleading. D(ivision) has equal rank with M(ultiplication). So because they have equal associativity they evalute from left to right.
Therefore 2*5/2 == 10/2 == 5.
A(ddition) and S(ubtraction) also have equal rank so the rule should more look like (B)(O)(DM)(AS). But that is less mnemonic.
2
In C, multiplication and division have equivalent precedence. Operator Precedence
i
in your example should return 5 since the operations will be
2 * 5 = 10
10 / 2 = 5
Consider it a very important lesson to use parenthesis whenever order of evaluation is critical.
Relying upon the implicit truncation of the integer value may (but probably won’t) have compiler specific behavior depending upon whether the C99 standard has been implemented. Kevin Cline posted an SO link that goes into further detail.
Some folk (like me) avoid relying on functionality that can change with the compiler. Others are more familiar with the compilers they are using and safely rely upon that type of functionality. YMMV.
3
Always put () around any expressions, even if they “should work”. Make more maintainable and stable code. Same with {}.