Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is causing "warning: pointer/integer type mismatch in conditional expression"?

Tags:

c

enums

macros

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.

like image 342
boltup_im_coding Avatar asked Nov 10 '12 01:11

boltup_im_coding


1 Answers

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 is int, but if it isn't then the type is const char *. This is a problem, because there is no automatic conversion from pointer to int (and vice versa). So the compiler warns about it.

The solution is to make sure that no matter what the value of fruit is, the value of KEY_TO_VALUE has a single type. For example, instead of "Undefined" (which is of type const char *, because it is a literal string), you can use a special value such as -1.

Also, note that APPLE is a constant with the value 0, ORANGE is a constant with the value 1 and BANANA is a constant with the value 2 (this is how enum works). So you don't need KEY_TO_VALUE, as the constants already have the desired values. You can simply compare fruit to APPLE directly:

if (fruit == APPLE) { ... }
like image 134
Omri Barel Avatar answered Sep 27 '22 23:09

Omri Barel