Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling operations with macros in C

Tags:

c

macros

I'm new to dealing with Macros and I've just stumbled into an exercise that I can't figure it out. Could someone explain to me what's happening here? If I compile i can see what the output is but i can't get it there myself. Thank you in advance!

#define M(varname, index) ( ( (unsigned char*) & varname )[index] ) 

int main(void) {
int a = 0x12345678; 
printf( "%x %x\n", M(a,0), M(a,3) );
printf( "%x %x\n", M(a,1), M(a,2) );
}
like image 563
kasedaime Avatar asked Jan 06 '23 20:01

kasedaime


1 Answers

Each Macro usage M(x,y) is replaced with ( (unsigned char*) & x )[y]

So your code looks like this after preprocessing:

int main(void) {
    int a = 0x12345678; 
    printf( "%x %x\n", ( (unsigned char*) & a )[0], ( (unsigned char*) & a )[3] );
    printf( "%x %x\n", ( (unsigned char*) & a )[1], ( (unsigned char*) & a )[2] );
}

Like Thomas B Preusser added in the OP Question comments, most C compiler suites allow to get the pre-processed code with certain compiler flags or tools like f.e. with GCC as mentioned here.

like image 192
makadev Avatar answered Jan 12 '23 03:01

makadev