Reputation: 165
What should be the output of the following code and why? I am little bit confused.
int a =10;
printf("%d %d %d",a,a=a+10,a);
Upvotes: 5
Views: 383
Reputation: 185980
The output is indeterminate, because a=a+10
is a side-effect, and the compiler is free to evaluate it before or after any of the other parameters.
EDIT: As David points out, the behaviour is actually undefined, which means all bets are off and you should never write such code. In practice, the compiler will almost always do something plausible and unpredictable, maybe even differing between debug and optimised builds. I don't think a sperm whale is a likely outcome. Petunias? Perhaps.
Upvotes: 20
Reputation: 59461
The order of evaluation for a, b, and c in a function call
f(a,b,c)
is unspecified.
Read about sequence points to get a better idea: (The undefined behavior in this particular case is not due to sequence points. Thanks to @stusmith for pointing that out)
A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are often mentioned in reference to C and C++, because the result of some expressions can depend on the order of evaluation of their subexpressions. Adding one or more sequence points is one method of ensuring a consistent result, because this restricts the possible orders of evaluation.
Sequence points also come into play when the same variable is modified more than once. An often-cited example is the expression
i=i++
, which both assignsi
to itself and incrementsi
; what is the final value ofi
? Language definitions might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior.
Upvotes: 11
Reputation: 165
Thanks for the answers.... :) The behavior is really undefined and compiler dependent. Here are some outputs
Compiled with Turbo c : 20 20 10
Compiled with Visual Studio c++: 20 20 20
Compiled with CC: 20 20 20
Compiled with gcc: 20 20 20
Compiled with dev c++: 20 20 10
Upvotes: 9
Reputation: 11038
Not to amend previous correct answers, but a little additional information: according to the Standard, even this would be undefined:
int a =10;
printf("%d %d %d", a = 20, a = 20, a = 20);
Upvotes: 2
Reputation: 37172
It is highly compiler dependent.
Because evaluation order of arguments is not specified by standard.
Upvotes: 1
Reputation: 79013
Not defined.
The evaluation order of a function parameters is not defined by the standard.
So the output of this could be anything.
Upvotes: 4