无法理解,如何评估以下语句:
++*++ptr and *ptr++++
根据我的理解,首先会给我所需的 lValue,因为在应用 * 后,它将给出不能用于++ 运算符的值。但是,结果却相反。请解释一下。
第二条语句给了我错误:batch3.c:6:21:错误:需要左值作为增量操作数 printf("%d", *ptr++++);
最佳答案
首先,一些standardese :
6.5.2.4 Postfix increment and decrement operators
Constraints
1 The operand of the postfix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue.
Semantics
2 The result of the postfix++
operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The value computation of the result is sequenced before the side effect of updating the stored value of the operand. With respect to an indeterminately-sequenced function call, the operation of postfix++
is a single evaluation. Postfix++
on an object with atomic type is a read-modify-write operation withmemory_order_seq_cst
memory order semantics.98)
...
6.5.16 Assignment operators
...
3 An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment,111) but is not an lvalue. The type of an assignment expression is the type the left operand would have after lvalue conversion. The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.
强调我的。
这堵文本墙的结果是表达式 ptr++
和 ++ptr
的结果不是左值。但是,这两个表达式都会产生指针值,因此它们可能是一元 *
运算符的操作数,以及 *ptr++
和 *++ptr
可能是左值。
这就是 ++*++ptr
起作用的原因;您正在递增 *++ptr
的结果,这可能是左值。但是,*ptr++++
被解析为 *(((ptr)++)++)
(后缀 ++
的优先级高于一元 *
); ptr++
的结果是第二个 ++
的操作数,但由于 ptr++
的结果不是左值,编译器会提示。如果您将其编写为 (*ptr++)++
,则该表达式将有效。
简而言之:
++*++ptr - valid, equivalent to ++(*ptr++)
*++++ptr - invalid, equivalent to *(++(++ptr)), result of ++ptr is not an lvalue
++++*ptr - invalid, equivalent to ++(++(*ptr)), result of ++*ptr is not an lvalue
*ptr++++ - invalid, equivalent to *((ptr++)++), result pf ptr++ is not an lvalue
(*ptr)++++ - invalid, equivalent to ((*ptr)++)++, result of (*ptr)++ is not an lvalue
(*ptr++)++ - valid
关于c - 指针上多个增量运算符的求值顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27131756/