klem
klem

Reputation: 13

Error when defining a simple macro in c++

I'm new with using macros in c++. I wrote a short macro and I don't know what is wrong with it. Please help.

#include <iostream>
using namespace std;

#define start B(
#define end )
#define B(x) cout<<x; 


int main (int argc, char *argv[])
{
    start 2014 end
}

Upvotes: 0

Views: 182

Answers (1)

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67237

The C preprocessor does not work the way you expect. Macros are expanded in one pass, that means that the preprocessor will substitute "start" with "B(" and "end" with ")" and give the result to the compiler.

Since there is no second preprocessing pass, the intermediate result "B(2014)" will not be interpreted as a preprocessor macro. Instead, the C++ compiler sees a function call, which is not what you want.

Upvotes: 7

Related Questions