from Hacker News

Understanding effective type Aliasing in C [pdf]

by quelsolaar on 5/5/25, 7:03 PM with 18 comments

  • by cancerhacker on 5/7/25, 1:12 AM

    It’s fun to consider how C devolves into assembler. In my mind, C and its derivatives dissolve into 68K assembler as I’m writing or debugging. Thinking about code this way lets me get a feel for how all the bits all fit together.

    It seems like a lost art to think that way. It’s disturbing to me how many candidates couldn’t write Hello World and compile it from the command line.

    Everyone should spend some time with godbolt.org or better, the -save-temps compiler flag, to see how changes affect your generated code. Right now. I’ll wait. (Shakes cane at kids)

  • by pansa2 on 5/7/25, 3:54 AM

    > Any access of memory using a union, where the union includes the effective type of the memory is legal. Consider:

        union {
            int i;
            float f;
        } *u;
        float f = 3.14;
        u = &f;
        x = u->i;
    
    > In this case the memory pointed to by “u” has the declared effective type of int, and given that “u” is a union that contains int, the access using the “i” member is legal. It’s noteworthy in this that the “f” member of the union is never used, but only there to satisfy the requirement of having a member with a type compatible with the effective type.

    Is this a typo? Should it say "declared effective type of float" and "“u” is a union that contains float"?

    It's interesting to see type-punning using a union - I've read that it should be avoided and to use `memcpy` instead. Are there any issues with the union approach in C? Or is the advice to prefer `memcpy` specific to C++, where AFAICT the union approach is undefined behaviour?

  • by 0xCE0 on 5/8/25, 4:13 PM

  • by jklowden on 5/7/25, 1:53 PM

    What drugs were they on? Why on earth is there any distinction between variables allocated statically, on the stack, or on the heap? I allocate a struct, copy data to it, and those data have no Effective Type? Because I started with malloc? Give me a break.

    The point of the type system is to define types. It’s not to make the compiler’s job easier, or to give standards committees clouds to build their castles on. No amount of words will justify this misbegotten misinvention.