C语言 C 宏:#if 检查相等性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2303963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:33:29  来源:igfitidea点击:

C macro: #if check for equality

cmacrosif-statement

提问by anon

Is there a way to do check for numerical equality in macros?

有没有办法检查宏中的数值相等性?

I want to do something like

我想做类似的事情

#define choice 3

#if choice == 3
  ....
#endif

#if choice == 4
 ...
#endif

Does C macros have support for things like this?

C 宏是否支持这样的事情?

回答by David R Tribble

Another way to write your code uses chained #elifdirectives:

另一种编写代码的方法是使用链式#elif指令:

#if choice == 3
  ...
#elif choice == 4
  ...
#else
  #error Unsupported choice setting
#endif

Note that if choiceis not #defined, the compiler (preprocessor) treats it as having the value 0.

请注意,如果choice不是#defined,则编译器(预处理器)将其视为具有值0

回答by wallyk

Indeed that should work. See http://gcc.gnu.org/onlinedocs/cpp/If.html#If

确实应该可以。见 http://gcc.gnu.org/onlinedocs/cpp/If.html#If

That reference is accurate, but written in "standards format":  abstractly without examples.

该参考是准确的,但以“标准格式”编写:抽象地没有示例。

回答by Nicolas Guillaume

As far as i know that should work. What compiler are you using ?

据我所知,这应该有效。你用的是什么编译器?

PS : Just for information, the defines names are usually written in caps !

PS:仅供参考,定义名称通常用大写!

#define CHOICE 3

#define CHOICE 3