简体   繁体   English

使用C中的宏处理操作

[英]handling operations with macros in C

I'm new to dealing with Macros and I've just stumbled into an exercise that I can't figure it out. 我刚开始处理Macros而且我偶然发现了一个我无法理解的练习。 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) );
}

Each Macro usage M(x,y) is replaced with ( (unsigned char*) & x )[y] 每个宏用法M(x,y)替换为( (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 fe with GCC as mentioned here. 就像Thomas B Preusser在OP问题评论中添加的那样,大多数C编译器套件允许使用某些编译器标志或工具来获取预处理代码,例如此处提到的带有GCC的 fe

Macros work by replacing one thing with another before attempting to compile the code (preprocessing). 在尝试编译代码(预处理)之前,宏通过将一个东西替换为另一个东西来工作。 So in the example you gave: 所以在你给出的例子中:

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

Each time a M(varname, index) occurs, it will be replaced by ( (unsigned char*) & varname )[index] 每次出现M(varname, index)时,它将替换为( (unsigned char*) & varname )[index]

In terms of what the code is doing, as an example (reformatted slightly for readability): 就代码的作用而言,作为示例(为了可读性而略微重新格式化):

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

This: 这个:

  • takes the address of variable a 获取变量a的地址
  • casts the address to an unsigned char* 将地址强制转换为unsigned char*
  • gets the 0th element in this pointer/array 获取此指针/数组中的第0个元素
  • formats it into the string, replacing the first %x , as hex ( %x is for hex) 将其格式化为字符串,将第一个%x替换为十六进制( %x表示十六进制)

It repeats this for the 3rd element with the second %x 它用第二个%x重复第三个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM