I am reading a book to learn C. In that book is the following example code giving a preprocessor error with gcc (Debian 4.7.2-4) 4.7.2. The error is
file.c: In function ‘main’:
file.c:16:14: error: token ""I know the C language.\n"" is not valid in preprocessor expressions
file.c:20:14: error: token ""I know BASIC.\n"" is not valid in preprocessor expressions
The code is:
#include <stdio.h>
#define C_LANG 'C'
#define B_LANG 'B'
#define NO_ERROR 0
int main(void)
{
#if C_LANG == 'C' && B_LANG == 'B'
#undef C_LANG
#define C_LANG "I know the C language.\n"
#undef B_LANG
#define B_LANG "I know BASIC.\n"
printf("%s%s", C_LANG, B_LANG);
#elif C_LANG == 'C'
#undef C_LANG
#define C_LANG "I only know C language.\n"
printf("%s", C_LANG);
#elif B_LANG == 'B'
#undef B_LANG
#define B_LANG "I only know BASIC.\n"
printf("%s", B_LANG);
#else
printf("I don't know C or BASIC.\n");
#endif
return NO_ERROR;
}
Is the gcc preprocessor incapable of doing this correctly or is the something wrong with the code that needs to be changed?
#elif "I know the C language.\n" == 'C'
and then failing on that. ideone fails it too. – cebarth May 20 '13 at 18:39gcc
seems to evaluate the conditional expression in theelif
even when the previousif
has been checked to be non-zero, but I would maybe suggest that this sort of edge case isn't important. I think if you ever wanted code like this you'd at least want to use two different macro definitions like BLUEPIXY suggests. Also, I think if the book stated clearly at the beginning that it was using a different compiler, that you can't really fault it for that. – roliu May 20 '13 at 19:52