Macias
Macias

Reputation: 717

Is it possible to replace the whole line with #define?

Let's assume that I have a program with many files and many cout's, and for debug purposes I would like to disable output for a moment, but only in a single file.

It is just out of curiosity question, I know that I shouldn't do that to disable output, but I started to wonder when facing this problem, and it only shows properly what I mean.

I tried to create a #define macro, but I can't replace the whole line, only a single symbol (with params).

For example:

//some common header file
#ifdef DISABLE_OUTPUT
#define cout... void; //?? DK exactly what should i put here
#endif

//other file
#include "commons.h" //my macro
#define DISABLE_OUTPUT

void foo()
{
    ...
    cout << "blablabla" << 4 << "something" << endl; // should be removed
    ...
}

If DISABLE_OUTPUT is defined, the whole line should be replaced with void; (better clear the line).

The problem is that I don't know how to clear the whole line with #define.

Is there any "magic" symbol or trick that I can use?

Upvotes: 0

Views: 504

Answers (1)

Daniel H
Daniel H

Reputation: 7463

It’s a bad idea to define a macro with the same name as a standard library component, so you shouldn’t #define cout at all. I’m going to assume you #define disableable_cout instead.

The simplest answer would be to define it like this:

#ifdef DISABLE_OUTPUT
#define disableable_cout if (false) cout
#else
#define disableable_cout cout
#endif

And then update the cout line in foo to this:

disableable_cout << "blablabla" << 4 << "something" << endl;

Which would expand to either this:

if (false) cout << "blablabla" << 4 << "something" << endl;

if DISABLE_OUTPUT is defined, or to this:

cout << "blablabla" << 4 << "something" << endl;

if DISABLE_OUTPUT were not defined.

Then, if DISABLE_OUTPUT is defined, the output line is skipped; if not, it will happen.

Alternately, you could require DISABLE_OUTPUT is always defined, to either 0 (don’t disable) or 1 (do disable). Then you could use a single definition, like this:

#define disableable_cout if (!DISABLE_OUTPUT) cout

Note that, either option is fragile, like most macros, but it should work in the typical case.

Upvotes: 3

Related Questions