这是" * PTR ++ = * PTR + A"未定义行为? [英] Is this "*ptr++ = *ptr + a" undefined behavior?

查看:142
本文介绍了这是" * PTR ++ = * PTR + A"未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我不是真的在这个答案的严重的需要,我只是好奇。

Well, I'm not really in serious need of this answer, I am just inquisitive.

防爆pressions像 * PTR ++ = A 是完全有效的,因为我们是在两个对象操作 PTR * PTR ,但如果我写 * PTR ++ = * PTR + A 是否仍然有效?

Expressions like *ptr++ = a are perfectly valid since we are operating on two objects ptr and *ptr but if i write *ptr++ = *ptr + a is it still valid ?

例如考虑下面的代码片段:

For example consider the following snippet:

int main(void){
   int a[] = {5,7,8,9,2};

   int* p =a;

   *p++ = 76; /*altering the first element */
   *p++ = *p + 32; /*altering the second element */    

   p = a;
   int i;
   for(i = 0;i<5; i++)
      printf("%d ",*p++);

   return 0;
}

我觉得没有什么可担心与前任pression * P ++ = * P + 32; ,但我不能确定所涉及的序列点。

I think that there is nothing to worry about with the expression *p++ = *p + 32; but I am unsure about the sequence points involved.

推荐答案

首先,让我们假设P为指针类型。结果
否则,所有的操作都​​是函数调用只是语法糖。

First let us assume that 'p' is a pointer type.
Otherwise all the operation are just syntactic sugar for function calls.

让我们打破语句分解成部分。

Lets us break the statement down into parts.

int* p = a;

*p++ = *p + 32;

<< Sequence Point >>
// Part 1: p++
// Note the definition of post increment in the standard is (5.2.6)
// The result of the expression p++ is the value of 'p' while the value of the 
// objects represented by 'p' is incremented. This can be represented in pseudo code as:
(A) int*  p1 = p;
(B) p = p + 1;

// Part 2: *p (On the result of Part 1) (On *p++)
(C) int& p2 = *p1;  // Note the use of p1;

// Part 3: *p (On *p + 32)
// Note: There is no linkage between this use of 'p' and the 'p' in Part 1&2
(D) int& p3 = *p;

// Part 4: *p + 32;
(E) int p5 = p3 + 32; // Note the use of p3;

// Part 5: Assignment.
(F) p2 = p5;
<< Sequence Point >>

Ordering that must be preserved:
(A) Before (B)
(A) Before (C)
(D) Before (E)
(C) Before (F)
(E) Before (F)

鉴于上述制约因素:结果
编译器可以重新排序在几个方面这些指令,结果
但要注意的要点是(B)可能发生的任何地方(B)的唯一限制是它(a)之后发生这样的作为(D)定义的P3的值可以根据两个不同的值之一(二)准确位置。

Given the above constraints:
The compiler can re-order those instructions in several ways,
But the main point to note is that (B) can happen anywhere the only constraint on (B) is that it happen after (A) Thus the value of p3 as defined in (D) could be one of two different values depending on the exact position of (B).

为P3的值不能被在此定义。结果
由此产生的语句未定义的行为。

As the value of p3 can not be defined here.
The resulting statement has undefined behavior.

这篇关于这是&QUOT; * PTR ++ = * PTR + A&QUOT;未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆