Home > Software engineering >  Preprocessor commands not working in C language
Preprocessor commands not working in C language

Time:10-17

While compiling this program it's giving the error message.

error: token ""India"" is not valid in preprocessor expressions.

but there's no syntax mistake in #define COUNTRY "India" also it's NOT showing this error message when I'm using single quotes

And it's also showing an error message in the last printf(); and multiple warnings too.

warning: character constant too long for its type

error: expected declaration specifiers or '...' before string constant

The last three printf()'s and last two preprocessor commands are completely greyed out also.


#define COUNTRY "India"

#if COUNTRY == "USA"
    printf("US Dollars");

#elif COUNTRY == "Bangladesh"
    printf("Bangladeshi Rupees");

#elif COUNTRY == "Nepal"
    printf("Nepali Rupees");

#else
    printf("Indian Rupees");

#endif

CodePudding user response:

[From a comment] could you please share the resource where it's stated that preprocessor can't compare strings?

No error is reported for #define COUNTRY "India" because preprocessor macros may be defined to be any tokens—they do not have to be numbers; they can be strings or operators or multiple tokens of various kinds.

An error is reported for #if COUNTRY == "USA" because the #if directive requires a constant-expression. This is specified in the 2018 C standard, in clause 6.10, paragraph 1. 6.10.1 1 further specifies that it shall be an integer constant expression (except that it may also contain defined identifier and defined ( identifier ).

6.6 6 says:

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts…

The string literals "India" and "USA" are not integer constants, enumeration constants, character constants, sizeof expressions, _Alignof expressions, or floating constants. Therefore, #if COUNTRY == "USA" violates the constraints of the C standard.

Additionally, note that C does not compare strings with the == operator. In "India" == "USA", each string literal would be converted to the address of its first element, and then those two addresses would be compared. Of course, any two different strings will always have different addresses. However, in "USA" == "USA", the C standard does not specify whether there are two arrays both containing “USA” or just one array, so the == could evaluate to either true or false. So not use == for comparing strings. You can use strcmp, declared in the <string.h> header. (But it still cannot be used in a #if directive.)

  • Related