Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C macro: #if check for equality

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?

like image 443
anon Avatar asked Feb 20 '10 22:02

anon


People also ask

What are the macros in C?

Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.

Why macro are used in C?

In C, the macro is used to define any constant value or any variable with its value in the entire program that will be replaced by this macro name, where macro contains the set of code that will be called when the macro name is used in the program.

What is macro in C give example?

A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive. Here's an example. Here, when we use c in our program, it is replaced with 299792458 .


3 Answers

Another way to write your code uses chained #elif directives:

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

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

like image 146
David R Tribble Avatar answered Oct 09 '22 19:10

David R Tribble


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

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

like image 44
wallyk Avatar answered Oct 09 '22 21:10

wallyk


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 !

#define CHOICE 3

like image 32
Nicolas Guillaume Avatar answered Oct 09 '22 19:10

Nicolas Guillaume