I realize there are lots of "Is this pointer madness defined behavior in C?" questions on this site, but none of the ones I found seemed to be on point, so if this is a duplicate I apologize.
Let's say I have two struct types Foo and Bar, with Foo having some field int baz. They have the same alignment, but one isn't an extension of the other, so casting a pointer to one to a pointer to the other and dereferencing would definitely be undefined. However, if I cast that pointer back and then dereference it, would that be an issue? I realize this isn't a good idea, but assuming for the moment I have to do it anyways, is the following code defined behavior?
int Get_Baz_With_Weird_Type_Stuff(Foo* fooPtr) {
Bar* barPtr;
Foo* fooPtr2;
barPtr = (Bar*) fooPtr;
fooPtr2 = (Foo*) barPtr;
return fooPtr2->baz;
}
Another use case I need to know is casting through function arguments like this
int Get_Baz_But_With_Weird_Type_Stuff(Bar* barPtr) {
Foo* fooPtr = barPtr;
return fooPtr->baz;
}
int Get_Value(Bar* bar, int (*callback)(Bar*)) {
return callback(bar);
}
int Get_Baz_In_Overly_Complicated_Way_For_Some_Reason(Foo* foo) {
return Get_Value((Bar*) foo, &Get_Baz_But_With_Weird_Type_Stuff);
}