0

Consider this code:

struct Point {
  double x;
  double y;
  double z;

  void setByIndex(int i, double value) {
      (&x)[i] = value;
  }
};

The setByIndex() function works and does what I want. But can I be sure this is not a UB (when called with a proper i)? Could you please provide references to the standard with the explanation?

Mikhail
  • 20,685
  • 7
  • 70
  • 146
  • I guess it is a duplicate: https://stackoverflow.com/q/8377667/10553341 – Damien Nov 24 '20 at 16:35
  • 2
    `Is it legal to access class members as an array?` No, that's undefiend behavior. `can I be sure this is not a UB` You can be sure this is UB. `Could you please provide references to the standard with the explanation?` The `Is it legal to index into a struct?` duplicate has them all, [expr/4](http://eel.is/c++draft/expr.add#4) would the most important. – KamilCuk Nov 24 '20 at 16:37
  • You are looking for the location (address) of an element of a structure. One of the issues is that the compiler can add padding between elements of a structure (for example, for alignment purposes). Another issue is that elements of a structure can be of different types; which makes the pointer value calculation difficult. When you have a pointer to an int, incrementing and (pointer math) is based on units of "int" size. What happens when you have int as one element and a struct as the next? – Thomas Matthews Nov 24 '20 at 17:59
  • @ThomasMatthews I mean this specific example. I already understood this is UB. I wonder though, does it change if I add `#pragma pack` to ensure there is no padding? – Mikhail Nov 25 '20 at 11:05
  • If you want to access the elements like an array, use `std::vector`, not `struct` or place them into a `vector` inside the struct. – Thomas Matthews Nov 25 '20 at 16:18
  • @ThomasMatthews well, with all due respect, this is a bragging, not an answer :) – Mikhail Nov 26 '20 at 11:05
  • @Mikhail: I'm not bragging. Your struct has 3 fields with identical types in succession. This fits the pattern of an array or a vector. – Thomas Matthews Nov 26 '20 at 19:07

0 Answers0