Is this use of unions strictly conforming?

前端 未结 4 662
攒了一身酷
攒了一身酷 2021-02-02 12:47

Given the code:

struct s1 {unsigned short x;};
struct s2 {unsigned short x;};
union s1s2 { struct s1 v1; struct s2 v2; };

static int read_s1x(struct s1 *p) { re         


        
4条回答
  •  野性不改
    2021-02-02 13:25

    I didn't read the standard, but playing with pointers in a strict-aliasing mode (ie, using -fstrict-alising) is dangerous. See the gcc online doc:

    Pay special attention to code like this:

    union a_union {
      int i;
      double d;
    };
    
    int f() {
      union a_union t;
      t.d = 3.0;
      return t.i;
    }
    

    The practice of reading from a different union member than the one most recently written to (called type-punning) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So, the code above works as expected. See Structures unions enumerations and bit-fields implementation. However, this code might not:

    int f() {
       union a_union t;
       int* ip;
       t.d = 3.0;
       ip = &t.i;
       return *ip;
    }
    

    Similarly, access by taking the address, casting the resulting pointer and dereferencing the result has undefined behavior, even if the cast uses a union type, e.g.:

    int f() {
      double d = 3.0;
      return ((union a_union *) &d)->i;
    }
    

    The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.

    Found anything similar in the second example huh?

提交回复
热议问题