Macro Processing Operations in C

I'm new to macros, and I just stumbled upon an exercise that I cannot understand. Can someone explain to me what is going on here? If I compile, I can see what the output is, but I cannot get it 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) );
}
+4
source share
2 answers

Each use of the macro M(x,y)is replaced by( (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] );
}

, OP, C , f.e. GCC, .

+6

, , ( ). , , :

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

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

, , ( ):

printf("%x %x\n", ((unsigned char*) &a)[0], ((unsigned char*) &a)[3]);

:

  • a
  • unsigned char*
  • 0- /​​
  • , %x, hex (%x hex)

%x

+3

All Articles