Comparing the first element of an enum and a pointer
Posted on 2011-08-12
I just had a very stupid bug in a lighttpd2 “feature” i was working on, it looked like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
typedef enum {
S_DEAD,
S_START
/* ... */
} con_state;
typedef struct {
con_state state;
/* ... */
} con;
void foo(con *c) {
if (S_DEAD == c) {
/* ... */
}
}
|
I obviously wanted to check c->state
, not c
– and i didn’t even get a warning from my compiler (neither gcc nor clang). Comparing with S_START resulted in this compiler warning:
1 |
[...] warning: comparison between pointer and integer [enabled by default]
|
My guess is that it doesn’t warn when you compare pointers with 0, and S_DEAD as the first value in the enum corresponds to the number 0. Comparing with S_START is similar to comparing with 1.
It should still print a warning of course – an enum member is obviously not a pointer.