Hi All,

I am using Visal Studio 2005. I couldnt understand how Visual Studio is executing follwing code. Can anybody please tel me. I have worked on Turbo C compiler, VC++ compiler and Visual studio. I could understand the output of other two compilers for the following code. But i couldnt understand the same of Visual studio.

int i=5;
printf("%d %d %d %d %d %d\n",i,i--,--i,i++,--i,i++);

That's because for each integer printed, all operations will be executed.
For example, with me this would give the following output: 4 5 4 5 4 5 The first integer printed, is the result of all the following operations, executed directly after each other: i,i--,--i,i++,--i,i++
Let's step through this: At the beginning of the program, integer variable i is set to value 5, then after executing i, it's value won't change, then we encounter i--, i's value won't change directly here (only at the end of the expression, because we used it as a postfix operator), the value is still 5 at this point, then we come across --i, because we used the prefix operator i's value will be decreased by 1, becoming 4 now, after that we see: i++, this won't change i's value directly (only at the end of the expression), making the first integer printed 4.
The same applies to the other integers printed.

Edit::
This may not be the case on all compilers, but your compiler should give you a warning about this, when compiling with all warnings on, I get the following warnings, which directly explain what the problem is:

t.c: In function ‘main’:
t.c:6: warning: operation on ‘i’ may be undefined
t.c:6: warning: operation on ‘i’ may be undefined
t.c:6: warning: operation on ‘i’ may be undefined
t.c:6: warning: operation on ‘i’ may be undefined
t.c:6: warning: operation on ‘i’ may be undefined

There is no point in understanding the output. It's undefined behavior. The output could be different the next time you run the program. UB also makes the rest of the program undefined so you have to understand all of that craziness too. It's a waste of resources to understand UB, just don't invoke it with stuff like this. ;)

commented: yep. +12
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.