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?
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.
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.
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 .
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
.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With