|
|
发表于 2006-1-11 18:13:07
|
显示全部楼层
楼主看来是对C标准还是很熟悉的样子,但是这儿不仅仅是与++运算有关,这是与整个表达式的求值顺序有关,而这是未定义的,不知道有没有看过《The C Programming Language》,这是我从中抄下来的一段:
- [The C Programming Language(2e)
- <2.12 Precedence and Order of Evaluation> P.52]
- C, like most languages, does not specify the order in which
- the operands of an operator are evaluated. (The exceptions are
- &&, ||, ?:, and ','.) For example, in a statement like
- x = f() + g();
- f may be evaluated before g or vice versa; thus if either f or
- alters a variable on which the other depends, x can depend on
- the order of evaluation. Intermediate results can be stored in
- temporary variables to ensure a particular sequence.
- Similarly, the order in which function arguments are evaluated
- is not specified, so the statement
- printf("%d %d\n", ++n, power(2,n)); /* WRONG */
- can produce different result with different compilers, depending
- on whether n is incremented before power is called. The solution,
- of course, is to write
- ++n;
- printf("%d %d\n", n, power(2, n));
- Function calls, nested assignment statements, and increment and
- decrement operators cause "side effects"--some variable is changed
- as a by-product of the evaluation of an expression. In any
- expression involving side effects, there can be subtle dependencies
- on the order in which variables taking part in the expression are
- updated. On unhappy situation is typified by the statement
- a[i] = i++;
- The question is whether the subscript is the old value of i or the
- new. Compilers can interpret this in different ways, and generate
- different answers depending on their interpretation. The standard
- intentionally leaves most such matters unspecified. When side
- effects (assignment to variables) take place within an expression
- is left to the discretion of the compiler, since the best order
- depends strongly on machine architecture. (The standard does specify
- that all side effects on arguments take effect before a function is
- called, but that would not help in the call to printf above.)
- The moral is that writing code that depends on order of evaluation
- is a bad programming practice in any language. Naturally, it is
- necessary to know what tings to avoid, but if you don't know how they
- are done on various machines, you won't be tempted to take advantage
- of a particular implementation.
复制代码 |
|