Search code examples
c++type-punning

C++ type punning via fallback to C


I watched this excellent video

https://www.youtube.com/watch?v=_qzMpk-22cc

I wonder if we can do this instead of strange memset hack:

https://gcc.godbolt.org/z/uOmzBD

struct S{
    int a;
};

extern "C"{

static void fix(S *s){
    int *x = (int *) s;
    *x = 5;
}

}

int main(){
    S s;

    fix(&s);

    return s.a;
}

This fallback to C seems to be completely legal?

(please do not comment that this kind of type punning is legal in C++11 and above)


Solution

  • extern "C" just applies to the linkage of the symbol, it doesn't otherwise change the rules of C++.

    If it's UB in C++ (and it is), then it's UB, putting it in an extern "C" function doesn't change that. The body of the function is still bound by the rules of C++ if it's compiled by a C++ compiler.

    However if you have the body of the function in a separate library (or even CU) compiled with C, then the body of the function is bound by C rules. I cannot say with certainty, but I think this is UB in C also.