Member Avatar

Why does the following snippet produces different result than expected?

#include <stdio.h>

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

I compiled and run this code with Visual C++ 2010 and it produces the output

7 6 8

instead of

7 6 6

Why?

Recommended Answers

Why does the following snippet produces different result than expected?

Undefined behavior was invoked. Your expectations are invalid.

http://en.wikipedia.org/wiki/Undefined_behavior

Jump to Post

All 2 Replies

So you should do something like this:

include <stdio.h>

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

Output:

568

Then you have clear code points for expressions. Not that I would call postincrement and right after preincrement to be good style, better:

#include <stdio.h>

int main()
{
    int i = 5;
    printf("%d", i);
    printf("%d", ++i);
    printf("%d", i+=2);
    getchar();
}
Be a part of the DaniWeb community

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