how printf is working?

hi plz see the below program

#include<stdio.h>
int main()
{
int i=5;
printf("%d",i+++i);//o/p is 11 but i expected it will print i++=5+ i=5=10will get printed and then i will post incremented but its printed as 10?
}



#include<stdio.h>
int main()
{
int i=5;
printf("%d %d %d %d",++i,i--,i++,--i);
}
o/p is 5 5 4 4 why it is evaluating from right to left




why its showing error like L value required
#include<stdio.h>
{
int i=5;
printf("%d",i+++++i); //error L value required
}

plz explain me
Thats why you shouldn't write messy code.

First of all, use code tags, not output tags for code.

Second:

Suffix and postfix increment - ++C and C++ - have the same precedence, so whether it's
(i++)+i or i+(++i)is undefined. Also undefined is the value of the second i with (i++)+i - it may already be incremented, or it may be not.

++i,i--,i++,--i

again, the order in which variable changes take place here is left undefined.

i+++++i is possibly being read as i+ (++ (++i)), which would cause that error.

The bottomline is, never alter a variable more than once in the same expression.
Last edited on
printf("%d",i+++i);//o/p is 11 but i expected [...]
The behavior of (i++ +i) is undefined. The compiler can do whatever it wants.

o/p is 5 5 4 4 why it is evaluating from right to left
The behavior is doubly-undefined. Function arguments can be evaluated in any order and, again, the behavior of incrementing a variable more than once in an expression is undefined. After printf() returns, i could have any value.

printf("%d",i+++++i); //error L value required
You're not doing ((i++)+(++i)). The compiler grabs the longest chunks first. The expression you wrote is actually (((i++)++)+i), which is illegal.
Once again, ((i++)+(++i)) is undefined. Knowing the value of that expression doesn't say much.
All these questions were asked in interview

can you plz explain me clearly what you are trying to say.

i understood about i+++++i
plz kindly explain me remaining
Last edited on
I don't know how to make this even clearer than I or helios put it. If you mean interview as in "job interview", you should know all this already.
Topic archived. No new replies allowed.