According to precedence Postfix increment has higher precendence than <=
so when i run this program why do i get Output as 5?
Example
Instead it Should execute as
When a=1
Check While condition 1++<=1
Check While condition 2++<=2
and then printf should print 3
#include <stdio.h>
int main()
{
int a=1;
while(a++<=1)
while(a++<=2);
printf("%d",a);
return 0;
}
This is more to do with the semantics of the postfix operator++
than precedence.
1) Check outer while condition 1++<=1
. The LHS evaluates to 1
, so we move into the inner while
. a
is incremented to 2
.
2) Check inner while condition 2++<=2
. The LHS evaluates to 2
, the condition is satisfied. a
incremented to 3
.
3) Check inner while condition 3++<=2
. The LHS evaluates to 3
, the condition is not satisfied, a
is incremented to 4
. We move back to the outer loop.
4) Check outer loop condition 4++ <= 1
. This fails, the loops end, and a
is incremented to 5
.