0

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?

3
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by pyTony
0

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();
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.