开发者

Can you explain the Output?

What s开发者_开发知识库hould 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);


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.


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 assigns i to itself and increments i; what is the final value of i? 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.


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


Not defined.
The evaluation order of a function parameters is not defined by the standard.
So the output of this could be anything.


using Mingw Compiler in Bloodshed Dev C++ : 20 20 10


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);


It is highly compiler dependent.

Because evaluation order of arguments is not specified by standard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜