In a structure, is it legal to use one array field to access another one?

后端 未结 9 465
忘了有多久
忘了有多久 2020-12-24 01:43

As an example, consider the following structure:

struct S {
  int a[4];
  int b[4];
} s;

Would it be legal to write s.a[6] and

9条回答
  •  我在风中等你
    2020-12-24 02:22

    Short Answer: No. You're in the land of undefined behavior.

    Long Answer: No. But that doesn't mean that you can't access the data in other sketchier ways... if you're using GCC you can do something like the following (elaboration of dwillis's answer):

    struct __attribute__((packed,aligned(4))) Bad_Access {
        int arr1[3];
        int arr2[3];
    };
    

    and then you could access via (Godbolt source+asm):

    int x = ((int*)ba_pointer)[4];
    

    But that cast violates strict aliasing so is only safe with g++ -fno-strict-aliasing. You can cast a struct pointer to a pointer to the first member, but then you're back in the UB boat because you're accessing outside the first member.

    Alternatively, just don't do that. Save a future programmer (probably yourself) the heartache of that mess.

    Also, while we're at it, why not use std::vector? It's not fool-proof, but on the back-end it has guards to prevent such bad behavior.

    Addendum:

    If you're really concerned about performance:

    Let's say you have two same-typed pointers that you're accessing. The compiler will more than likely assume that both pointers have the chance to interfere, and will instantiate additional logic to protect you from doing something dumb.

    If you solemnly swear to the compiler that you're not trying to alias, the compiler will reward you handsomely: Does the restrict keyword provide significant benefits in gcc / g++

    Conclusion: Don't be evil; your future self, and the compiler will thank you.

提交回复
热议问题