开发者

undefined behaviour in C [duplicate]

This question already has answers here: 开发者_如何学Python Closed 11 years ago.

Possible Duplicates:

Parameter evaluation order before a function calling in C

order of evaluation of function parameters

What will be the output of the following code:

n=5;
printf("%d %d\n", ++n, power(2, n));

output=32

shoulld not be the output be 2^6 =64?

will different compilers give different result?


Order of evaluation of function arguments is unspecified. The compiler can compute the arguments in any order it pleases, but it must do it in some particular order (so there's no undefined behaviour here). The output can be either 32 or 64.

UPD: this is wrong, there's UB here, see here.


Contrary to what other answers say, the code may indeed exhibit undefined behavior.

As has been stated, the order of evaluation of function arguments is unspecified in C. In your program, you have an expression composed of several subexpressions:

ex0(ex1, ex2, ex3(ex4, ex5));

There is only a partial ordering between these subexpressions: ex4 and ex5 must obviously be evaluated before ex3 can be evaluated, and ex1, ex2, and ex3 must be evaluated before ex0 can be evaluated. Other than that, the order of evaluation of the subexpressions is unspecified, and it is up to your compiler to decide the order in which to evaluate the subexpressions.

There are certain, valid orders of evaluations that yield undefined behavior. For example, if ++n is evaluated before power(2, n), the results are undefined: there is a sequence point after the evaluation of all of the arguments to a function but not before or between, and the C Language Standard very clearly states (C99 §6.5/2; emphasis mine):

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

If ++n is evaluated first, this rule is violated because n is modified by ++n and n is read for the call to power(2, n) without a sequence point between those two steps.

A program that exhibits undefined behavior may produce any result: it may crash, it may print an unexpected answer, or it may appear to work as you expect it to work. Since your program potentially exhibits undefined behavior, it's difficult to discuss with certainty the actual behavior that you see. It is best to avoid writing programs that potentially (or worse, actually) exhibit undefined behavior.


And what does your power function contain? I just checked C math libraries pow function. I had to cast it to <int> like this;

#include <cstdio>
#include <cmath>
using namespace std;

int main () {
    int n=5;
    printf("%d %d\n", ++n, (int)pow(2.0, n));
    return 0;
}

Output: 6 64

I used Microsoft Compiler(used by Visual Studio). Hope it helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜