在C宏的范围是什么? [英] Scope of macros in C?

查看:156
本文介绍了在C宏的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将这些宏进行评估?

How these macros are evaluated?

# define i 20
void fun();

int main(){
  printf("%d",i);
  fun();
  printf("%d",i);
  return 0;
}

void fun(){
  #undef i
  #define i 30
}

给输出2020年,但而,

gives output as 2020 but whereas,

# define i 20
void fun(){
  #undef i
  #define i 30
}

int main(){
  printf("%d",i);
  fun();
  printf("%d",i);
  return 0;
}

给出输出3030。
请解释。谢谢你。

gives output as 3030. Please Explain. Thanks.

推荐答案

çpreprocessor作品从上到下不论函数调用。它是从点(线)中的任何定义宏的文件有效,直到相应民主基金或到翻译单元结束。

C Preprocessor works top to bottom irrespective of function calls. It is effective from that point (line) in whatever the file that macro is defined, until corresponding undef or till end of the translation unit.

所以,你的code将成为

So, your code would become,

# define i 20
               // from now on, all token i should become 20
void fun();
int main()
{
  printf("%d",i);   // printf("%d",20);
  fun();
  printf("%d",i);   // printf("%d",20);
  return 0;
}
void fun()
{
#undef i
              // from now on, forget token i
#define i 30
              // from now on, all token i should become 30
}

你的第二个code将成为

Your second code would become,

# define i 20
               // from now on, all token i should become 20
void fun()
{
#undef i
               // from now on, forget i
#define i 30
               // from now on, all token i should become 30
}
int main()
{
  printf("%d",i);    //  printf("%d",30);
  fun();
  printf("%d",i);    // printf("%d",30);
  return 0;
}

这篇关于在C宏的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆