In C++, is it valid to treat scalar members of a struct as if they comprised an array?

is this code legal?

No, it has undefined behavior. The expression &x is a float* that points to a float object and not to the first element of a float array. So, in case idx is 1 or 2 or some other value, the expression (&x)[idx] is (&x)[1] or (&x)[2] respectively which means you’re trying to access memory that is not meant to be accessed by you.

do any of the major compilers (G++, MSVC, Clang) offer any explicit or implicit guarantees that this code will work as intended?

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.

So the output that you’re seeing(maybe seeing) is a result of undefined behavior. And as i said don’t rely on the output of a program that has UB. The program may just crash.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.


1For a more technically accurate definition of undefined behavior see this, where it is mentioned that: there are no restrictions on the behavior of the program.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)