I have an enum, and a macro definition and a method that all use the enum. I can’t get it to compile. Consider the following pieces of code.
typedef enum fruits_t
{
APPLE,
ORANGE,
BANANA
} fruits_t;
#define KEY_TO_VALUE(x) ((x == APPLE) ? 0 : \
(x == ORANGE) ? 1 : \
(x == BANANA) ? 2 : \
"Undefined")
static void foo(char fruit) {
if (fruit == KEY_TO_VALUE(APPLE)) {
/* do something */
}
}
This compiles, but I get the following warnings.
warning: pointer/integer type mismatch in conditional expression
warning: comparison between pointer and integer
Why? I am very new to C, so if you could explain things that may seem obvious to an experienced C developer, I’d appreciate it. Most of my programming knowledge is Java based.
The compiler is trying to figure out the type of each expression in the program.
An expression such as
x > 0 ? 5 : "no"makes the compiler scratch its head. If x is greater than zero, the type isint, but if it isn’t then the type isconst char *. This is a problem, because there is no automatic conversion from pointer toint(and vice versa). So the compiler warns about it.The solution is to make sure that no matter what the value of
fruitis, the value ofKEY_TO_VALUEhas a single type. For example, instead of “Undefined” (which is of typeconst char *, because it is a literal string), you can use a special value such as -1.Also, note that
APPLEis a constant with the value 0,ORANGEis a constant with the value 1 andBANANAis a constant with the value 2 (this is howenumworks). So you don’t needKEY_TO_VALUE, as the constants already have the desired values. You can simply comparefruittoAPPLEdirectly: