Search code examples
cpointerscastingtype-punning

how do you do a type casting in one line in c?


how do you do a type casting in one line in c?

unsigned char num[4]={0,2}; //512 little endian
unsigned int * ptr = num;

printf("%u\n", *ptr); // 512

//trying to do the same underneath in one line but it dosen't work    
printf("%u\n", (unsigned int *)num); //


Solution

  • The same as

    unsigned int * ptr = num; printf("%u\n", *ptr); // !! nonportable, nonsafe (UB-invoking)
    

    in one line would be

    printf("%u\n", *(unsigned int *)num); // !! nonportable, nonsafe (UB-invoking)
    

    However both versions are nonportable and unsafe. They invoke undefined behavior by violating the strict aliasing rule and possibly by creating a pointer that's not suitably aligned.

    You can do it safely with memcpy:

    #include <stdio.h>
    #include <string.h>
    
    int main(){
        unsigned char num[4]={0,2}; //512 little endian
    
        #if 0
        //the unsafe versions
        unsigned int * ptr = num; printf("%u\n", *ptr);
        printf("%u\n", *(unsigned int *)num);
        #endif
    
        //the safe version using a compound literal as an anonymous temporary;
        //utilizes how memcpy returns the destination address
        printf("%u\n",*(unsigned*){memcpy(&(unsigned){0},&num,sizeof(num))});
    
    }