C macro: #if check for equality
Asked Answered
R

3

40

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?

Rania answered 20/2, 2010 at 22:14 Comment(3)
What did your compiler tell you?Grose
Better yet, what does the textbook / reference book say?Slumlord
@Grose My compiler is currently saying, "No, I don't support this." I'm trying to figure out why it's not working. So, your question is not helpful in my situation.Endocarp
M
30

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.

Maestoso answered 20/2, 2010 at 22:18 Comment(0)
F
43

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.

Ferreira answered 20/2, 2010 at 22:52 Comment(2)
How can we compare strings? Namely if I have a macro defined by #define MY_MACRO Hello. How can I make if to check its string value?Orthodoxy
The ISO C preprocessor does not have a way to compare strings.Ferreira
M
30

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.

Maestoso answered 20/2, 2010 at 22:18 Comment(0)
B
4

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

Bituminize answered 20/2, 2010 at 22:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.