Christian
Christian

Reputation: 315

#ifndef in C being ignored?

I have a bit of code where I want to have logging only if DEBUG is defined. So I though I might be able to replace a Token (here: "DEBUGLOG") with the comment string "//". But how to do?

    #ifndef DEBUG
     #define DEBUGLOG //
    #endif

[...] 
    DEBUGLOG        printf("Debug String"\n);
[...]

There is no definition of DEBUG somwhere else in the code. But my gcc compiles this line and the program itself executes the printf();

Why?

I tried to include it in parantheses like this, but it gets an compile error:

#ifndef DEBUG
 #define DEBUGLOG "//"
#endif

This is the compiler message:

beispiel.c:45:10: error: expected ‘;’ before ‘printf’
 DEBUGLOG printf("Debug String"\n);
          ^

Any hints?

Upvotes: 3

Views: 865

Answers (1)

P.W
P.W

Reputation: 26800

If you look up the Phases of translation, you will find that the Phase where preprocessor is executed (Phase 4) is after the phase where comments are replaced by a white space character (Phase 3).

Phase 3
1) The source file is decomposed into comments, sequences of whitespace characters (space, horizontal tab, new-line, vertical tab, and form-feed), and preprocessing tokens, which are the following
...
2) Each comment is replaced by one space character

Phase 4
1) Preprocessor is executed.

So in Phase 3 the line:

#define DEBUGLOG //

becomes:

#define DEBUGLOG 

And in Phase 4 the line:

DEBUGLOG        printf("Debug String"\n);

becomes:

printf("Debug String"\n);

And that is why your printf is executed.

And when you put it quotes ("//"), that line becomes:

"//"   printf("Debug String"\n);

The quotes ("") will not be removed. And this is a compiler error.

Upvotes: 3

Related Questions