Wednesday, 15 February 2012

c++ - Is this "*ptr++ = *ptr + a" undefined behavior? -


OK, I'm not really serious about this answer, I'm just curious.

As the expressions of * ptr ++ = a are fully valid because we have two objects ptr and * ptr But if I write * ptr ++ = * Ptr + a is it still valid?

For example, consider the following snippet:

  int main (zero) {int a [] = {5,7,8,9,2}; Int * p = a; * P ++ = 76; / * Change the first element * / * p ++ = * p + 32; / * Change the second element * / p = a; Int i; For (i = 0; i <5; i ++) printf ("% d", * p ++); Return 0; }  

I think the expression * p ++ = * p + 32; There is nothing to worry about , but I am not sure about the sequence points involved in it. First assume that 'p' is an indicator type. Otherwise all operations are there. Sentinative Chinese for Function Calls

Allows us to break the statement into parts.

  int * p = a; * P ++ = * P + 32; & Lt; & Lt; Sequence Point & gt; & Gt; // Part 1: Definition of post growth in P ++ // standard (5.2.6) // The result of the expression is the value of p ++ 'p', whereas the value of the // object represented by 'P' 'It can be represented in its pseudo code: (A) Int * P1 = P; (B) P = P + 1; // Part 2: * P (on the result of Part 1) (on * P ++) (C) Int'l; P2 = * p1; // pay attention to the use of p1; // Part 3: * P (* at P +32) // Note: There is no connection between this part of 'P' and 'P', Part 1 and 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; & Lt; & Lt; Sequence Point & gt; & Gt; The order should be protected: Before (B) (A) before (C) (D) before (E) (C) before (F) (E) (F)  

In view of the above obstacles:
compiler can order these instructions again in many ways, but the main point is that (b) can be anywhere (B) only The obstacle that happens is (A) after (A) according to the exact position of the value of P3 (B) defined in (D), in two different values One might.

As the value of p3 can not be defined here - as a result the statement has undefined behavior.


No comments:

Post a Comment