My [question] is since unary operator ++ has the highest precedence
(In the program above) why k has not been incremented twice ...
[/QUOTE]
Because of something known as "short circuit" evaluation. This is an
FAQ. See:
<
http://c-faq.com/expr/shortcircuit.html>
In addition, it is worth pointing out that:
- C does not, in a sense, even *have* "precedence and associativity",
in that the grammar in the C standards simply writes out all
the details instead of using a compressed, operator-precedence
grammar. Of course, the actual C grammar is equivalent to
various operator-precedence grammars, so a person can construct
one (or even several).
- in any case, though, "operator precedence" does *not* determine
actual runtime evaluation order. It merely tells you (the C
programmer) how the compiler must bind various operators in an
expression. It is up to the compiler to find any valid runtime
order of evaluation that computes the same answer as the expression
as-parsed.
Consider, as an example, the following code fragment:
int f(void) { puts("f()"); return 3; }
int g(void) { puts("g()"); return 4; }
...
int x = f() + g();
Which of f() or g() will be called first? Why? What if I add
an h() function and change the assignment to x:
int h(void) { puts("h()"); return 5; }
...
int x = f() + g() * h();
In what order will f(), g(), and h() be called? Why?
(Answer: the above contains what the Standard calls "unspecified
behavior". One of f(), g(), or h() will be called first, one will
be called second, and one will be called last, but it is not
specified which one, and it can change from one compiler to another,
or one compilation to the next, or even one run to the next. The
last is pretty unlikely, except in some C compilers that will be
written in the future to take advantage of multicore CPUs. So "any
of the three may be called first, as all six orders are possible,
and the reason why any particular order actually occurs is up to
the compiler.")