c++ - *p++ += 2 定义明确吗?

标签 c++ c pointers post-increment compound-assignment

我不确定下面的语句是否被标准 C 很好地定义了

*p1++ += 2;

或其他类似声明:

*E1++ <operator>= E2

来自标准 C 关于后增量:

The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand 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 side effect of updating the stored value of the operand shall occur between the previous and the next sequence point.

关于复数赋值:

A compound assignment of the form E1 op= E2 differs from the simple assignment expression E1 = E1 op (E2) only in that the lvalue E1 is evaluated only once.

最佳答案

让我们稍微重写一下以使其更清晰:

(*p1++) += 2

因此 p1 的旧值将被取消引用,并将 2 添加到其所指对象。并且 p1 将在它被取消引用后递增(或者至少在它的旧值被加载并等待被取消引用之后)。这里没有问题:没有一个部件被使用超过一次。

话虽如此,为了清晰起见,您应该考虑重写代码:

*p1 += 2;
++p1;

关于c++ - *p++ += 2 定义明确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26417120/

相关文章:

c - 动态和静态混合分配

c++ - 将 strtok 分隔符设置为两个字符

c++ - 如何以简洁的方式安全地访问容器中的每个第 n 个元素?

c++ - 每次运行程序时都使用相同的随机数

c - ';' token 之前应出现错误 '{'

c - 如何在 C 中完成自动数组的排序?

c++ - 将字符转换为 UTF-8 背后的逻辑

c++ - 我的二进制转换器有问题

C - 嵌套循环和堆栈?

C++ 将 const char* 转换为 char*