Ravi said:
> Hi,
>
> -I have some confusion on the order in which the operators are evaluated.
> A statement such as 7/9*9+6-4 is evaluated in which order ?
> -Which of the following is evaluated first:
> a) &&
> b) ||
> c) !
>
> Thanks
> Ravi
>
Thank you for these intelligent questions, Ravi.
7/9*9+6-4 is evaluated like this:
1. 7/9 = 0
2. 0*9 = 0
3. 0+6 = 6
4. 6-4 = 2 <--- Final answer is 2.
A technical explanation using common terms:
Two things in C which influence the order in which operations are
performed are "precedence" and "associativity."
1. "Precedence" is a ranking of operators.
2. "Associativity" is the direction in which operations
are performed.
a. "Left associativity" means to evaluate from left to right.
b. "Right associativity" means to evaluate from right to left.
The following is a chart from _C Programming: A Modern Approach_,
by K.N. King.
Precedence Name Symbol(s) Associativity
1 array subscripting [ ] left
1 function call ( ) left
1 structure and union member . -> left
1 increment (postfix) ++ left
1 decrement (postfix) -- left
___________________________________________________________________________
2 increment (prefix) ++ right
2 decrement (prefix) -- right
2 address of & right
2 indirection * right
2 unary plus + right
2 unary minus - right
2 bitwise complement ~ right
2 logical negation ! right
2 size sizeof right
___________________________________________________________________________
3 cast () right
___________________________________________________________________________
4 multiplicative * / % left
___________________________________________________________________________
5 additive + - left
____________________________________________________________________________
6 bitwise shift << >> left
____________________________________________________________________________
7 relational < > <= >= left
____________________________________________________________________________
8 equality == != left
____________________________________________________________________________
9 bitwise and & left
____________________________________________________________________________
10 bitwise exclusive or ^ left
____________________________________________________________________________
11 bitwise inclusive or | left
____________________________________________________________________________
12 logical and && left
____________________________________________________________________________
13 logical or || left
____________________________________________________________________________
14 conditional ?: right
____________________________________________________________________________
15 assignment = *= /= %= right
+= -= <<= >>=
&= ^= |=
_____________________________________________________________________________
16 comma , left
_____________________________________________________________________________
--Steve