c - 指针上多个增量运算符的求值顺序

标签 c pointers operators increment

无法理解,如何评估以下语句:

++*++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 with memory_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/

相关文章:

c - 程序因 "Segmentation fault"(11) 而终止

c++ - 在 C++ 中用类型为 'double' 的乘数将复数对象与实部和虚部相乘

c - 用 C 语言构建全双工管道

c - 在 C 中,如何访问此结构中的元素?

c++ - 段错误,你能帮我吗?

c - 我应该回收指针和引用还是创建新的?

java - == 或等于比较最终静态字段时

.net - 我在哪里可以获得有关 ! VB.Net 在 Linq to DataSet 中使用的运算符?

c - 求助 C 语言中的 gcvt 函数?

c - 只读取一个字符(避免换行),然后读取一个字符串(用于实现简单的 CLI