Member Avatar for Nirvin M

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?

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.