main()
{
int i=1;
printf("%d,%d,%d",i,i++,i++);
}

the o/p is 3,2,1.
But how it is possible In which order does printf executes??why it is not 1,2,3.

Recommended Answers

All 7 Replies

hi,

i think its so: first the third %d gets a 1 value because of i++, it has a postincrement so after that i = 2. Then the second %d gets the before modified i value thats 2, and it has also a postincrement so after that i = 3. Then there is no more incrementation so the first %d is 3.

an example for a 1,2,3 would be

i=3;

printf("%d %d %d",i,i--,i--);

ps.: as u see the evaluation goes from right to left... hope this helps u :)

actually it's undefined behavior
see this similar thread for clarifications and read WaitP and Narue's comments

Well.. m sorry to go against what u just said zeroliken, but it isnt undefined... Its how the prefix and postfix operators work..

int main()
    {
        int i=1;
        printf("%d,%d,%d",i,++i,++i);
        return 0;
     }

Try this and this should give u the output as 1,2,3.

Well.. m sorry to go against what u just said zeroliken, but it isnt undefined... Its how the prefix and postfix operators work..

Nope, it's definitely undefined because i is modified more than once between sequence points. The commas in a function call don't count as sequence points.

Try this and this should give u the output as 1,2,3.

Undefined behavior includes doing what you expect, so empirical "it works for me" evidence is completely worthless. In the case of undefined behavior, we must refer to what the language standard says.

int main()
{
int i=0;
printf("%d%d%d",i,i++,i++);
return(0);
}

+1 for undefined, cause printf in your project library maybe written differently or that can be compiler specific no ?
anyway why would someone write like that and care about it?? :))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.