Due to the way how memory is layout for structs
and its members, I was able to do the following:
typedef struct
{
int a;
int b;
int c;
} myStruct;
In main()
:
myStruct aStruct;
aStruct.a = 1;
aStruct.b = 2;
aStruct.c = 3;
int *aBadBoyPointer = &aStruct.a;
printf("%i %i %i", *(aBadBoyPointer), *(++aBadBoyPointer), *(++aBadBoyPointer));
Easy enough.
The above line causes a warning:
Unsequenced modification and access to
aBadBoyPointer
But it compiles and runs fine printing out 1, 2, 3
, respectively.
My question here:
For the sake of doing things correctly, could you cite a scenario where this would break miserably, a scenario that confirms the compiler that this is a bad practice / bad way of doing things?
Or: perhaps this is in fact a "a good way" to do things under some rare circumstances?
Addendum:
Aside from this part that cause Undefined Behavior:
printf("%i %i %i", *(aBadBoyPointer), *(++aBadBoyPointer), *(++aBadBoyPointer));
What I really like to know is:
Is it considered OK (a good practice) using a pointer pointing to one of the members of the
struct
but then gain access to other members within thestruct
this way (by incrementing, made possible due to the memory layout of thestruct
members) or is it a practice that is frowned upon by the Standard?
And secondly as mentioned above, if this is in deed a bad practice, would there ever be cases where using a pointer this way within a struct and then gain access to another member variable beneficial under certain circumstances?