I'd like to use a negative array index to access the same-type member that immediately precedes that array in a struct.
Consider this type of code:
union hello {
int a[2];
struct { int b0; int b1[1]; };
};
I want to use b1[-1]
to access b0
.
When I try to do this, clang and gcc seem to understand exactly what I want.
extern const int test = hello{{42, 1337}}.b1[-1];
This correctly determines at compile time that test
is really 42
.
Unfortunately, clang produces a warning that -1
is not in bound. Gcc does too if I change const
to constexpr
.
What is the correct way to write this type of code?
Here are the ways I already know but don't like:
- Use
a[]
with 1-based indexing. - Make
b1
a pointer that points toa[1]
.
Yes, but they also generate some diagnostic, if asked (gcc):
Also, accessing
b1
which is not the active member of the union (a
is the initialized one) is undefined behavior.You could instead write a class which encapsulates the data and the wanted access logic: