int i=0;
printf("%d %d %d %d",++i,++i,++i,++i);
output:
4 3 2 1
why is not
1 2 3 4
Printable View
int i=0;
printf("%d %d %d %d",++i,++i,++i,++i);
output:
4 3 2 1
why is not
1 2 3 4
because C doesn't guarantee that the first parameter of a function is evaluated before the second, and I think the behavior is undefined.
try something like:
Code:printf("%d %d %d %d",i+1,i+2,i+3,i+4);
i += 4;
You are correct. This is undefined behaviour. This means that it can be implemented in any way the compiler creator feels like because there is no standard definition of what is supposed to happen.Quote:
Originally posted by glUser3f
C doesn't guarantee that the first parameter of a function is evaluated before the second, and I think the behavior is undefined.
Thus, doing it this way makes your code unportable, and a pain to debug when something doesn't quite work the way you think it should. It may work the way you intend on one compiler/setup, but slightly or hugely different on another.
Quzah.
Not only is the order of evaluation of parameters undefined, multiple side effects are also undefined as well (basically ++ applied to the same object multiple times in the same expression).
http://www.eskimo.com/~scs/C-faq/s3.html
So you could end up with all the ++ happening first, and the output would be
4 4 4 4
I tried the code in both in lcc32 and gcc both are giving same output
but for below code
printf("%d %d",p(),k());
function p() is called first in both lcc and gcc.
> I tried the code in both in lcc32 and gcc both are giving same output
Ah, the "works for me" defence your honor.
So try it in Borland C, Mark Williams C, Lattice C, Visual C, Watcom C, Tiny C, etc, etc....Quote:
Originally posted by shiju
I tried the code in both in lcc32 and gcc both are giving same output
but for below code
printf("%d %d",p(),k());
function p() is called first in both lcc and gcc.
If you find one that doesn't give the same output, therein lies the portability problem.
I feel the ++ operator has higher precedence then ,(comma) operator.And ++ operator is evaluated from right to left.
thats why the statement
printf("%d %d %d %d",++i,++i,++i,++i);
is evaluated as
printf("%d %d %d %d",4,3,2,1);
please correct me if I am wrong
It's already been stated: It is undefined. It is up to the compiler to interpret this as it sees fit in regards to the specific way it's being used.Quote:
Originally posted by rakesh
Quzah.
printf("%d %d %d %d",++i,++i,++i,++i);
Gives 4 4 4 4 on MSVC.
An excellent article is available on this subject (it's more complicated than left to right or right to left):
http://www.embedded.com/story/OEG20020429S0037
>>I feel the ++ operator has higher precedence then ,(comma) operator.<<
You are confusing the 'comma operator' and the 'comma argument seperator'. There is no comma operator in the above statement.