Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))});

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading