Is this use of unions strictly conforming?

前端 未结 4 661
攒了一身酷
攒了一身酷 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:15

    It is not about conforming or not conforming - it one of the optimisation "traps". All of your data structures have been optimised out and you pass the same pointer to optimised out data so the the execution tree is reduced to simple printf of the value.

      sub rsp, 8
      mov esi, 4321
      mov edi, OFFSET FLAT:.LC0
      xor eax, eax
      call printf
      xor eax, eax
      add rsp, 8
      ret
    

    to change it you need to make this "transfer" function to be side effect prone and force the real assignments. It will force optimizer to not reduce those nodes in the execution tree:

    int test(union s1s2 *p1, union s1s2 *p2, volatile union s1s2 *p3)
    /* ....*/
    
    main:
      sub rsp, 8
      mov esi, 1234
      mov edi, OFFSET FLAT:.LC0
      xor eax, eax
      call printf
      xor eax, eax
      add rsp, 8
      ret
    

    it is quite trivial test just artificially made a bit more complicated.

提交回复
热议问题