Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comment after #else preprocessor directive

This is simple piece of C code and to my surprise it compiles successfully (at least in Visual Studio 2012 which I am using)

#include <stdio.h>

#define MYCONSTANT

int main(int argc, char* argv[])
{
    #ifdef MYCONSTANT // We can write anything here as comment
        printf("MYCONSTANT is defined");
    #else We can write any random words here without marking it as comment
        printf("MYCONSTANT is not defined");
    #endif

    return 0;
}

Question: Is writing anything after #else allowed this way?

like image 825
Atul Avatar asked Oct 29 '25 16:10

Atul


1 Answers

In standard C, you are not allowed to put anything except comments on the line after #else or #endif. With the compiler on my computer, I get a warning from your code by default:

test.c: In function ‘main’:
test.c:9:11: warning: extra tokens at end of #else directive [-Wendif-labels]
     #else We can write any random words here without marking it as comment
           ^~

and this becomes a hard error if I request strict conformance with C99.

However, the original "K&R" C preprocessor did allow arbitrary text to appear on the line after #else and #endif, and old programs would use that. Your compiler is being backward-compatible and allowing those old programs to compile without error.

Many C compilers allow lots of things that are nowadays considered bad style or outright wrong, by default, for the sake of allowing old code to keep working. Look through the manual for Visual Studio and see if there is a recommended configuration to use for new programs. I don't use VS myself so I can't give any more specific advice.

like image 97
zwol Avatar answered Nov 01 '25 06:11

zwol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!