简体   繁体   中英

Interpreting #define PRINTF if(false) printf in C++

I am analyzing the following macro in C++:

#define PRINTF if(false) printf

Does this mean, instead of typing printf(" .... "); one can just use PRINTF("...") ? Or is PRINTF activated only if a boolean in the code is true?

This seems to be made to toggle output on and off. As it currently stands,

PRINTF("What ever");

will never print anything as it expands to

if(false) printf("What ever");

You can then toggle output on by changing

#define PRINTF if(false) printf

to

#define PRINTF if(true) printf
#define PRINTF if(false) printf 

is a macro for PRINTF , which will replace the latter with

if(false) printf

in your code. So whenever you write

PRINTF("something")

it is translated to

if(false) printf("something")

ie, it is not executed. It is probably useful for debugging, when you may want your PRINTF "cancelled". To keep it displaying stuff, you'll just change the macro to

#define PRINTF if(true) printf

When ever you write

PRINTF("this does nothing" );

it would textually replace it by

if(false) printf("this does nothing" );

So basically it would do nothing as the condition is always false.

As others already told you, this is a way to switch output on and off.

However, it's a particulary error-prone way of doing so.

Consider the following piece of code:

#include <stdio.h>

#define PRINTF if(false) printf

int main()
{
    bool x = true;
    int i = 0;

    if (x) {
        PRINTF("What ever");
    else
        i = 1;
    }
}

Can you guess what i will be?

The answer is it will be 1 , because the compiler does not care about accidental wrong indentation, and the PRINTF macro expands as follows:

#include <stdio.h>

#define PRINTF if(false) printf

int main()
{
    bool x = true;
    int i = 0;

    if (x) {
        if(false) printf("What ever");
    else
        i = 1;
    }
}

Which is more easily read as:

#include <stdio.h>

#define PRINTF if(false) printf

int main()
{
    bool x = true;
    int i = 0;

    if (x) {
        if(false)
            printf("What ever");
        else
            i = 1;
    }
}

Macros are evil!

You should use a different way of toggling output anyway. In fact, you should not blindly turn off logging messages in "release" versions (which seems to be this macro's intent), because this is where you will later need them most. On the other hand, only the most basic toy applications should unconditionally use direct standard output with printf or std::cout . You should instead operate on std::ostream references. Search for related Stack Overflow questions about logging in C++. The topic is quite complex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM