Mario Zelic
Mario Zelic

Reputation: 229

Pre-processor parsing on C++

If we want to use user input to do something in a program, or print a result we need to

 #include <iostream>

otherwise, cout and cin will not be acknowledged by the compiler.However the command #include is a pre-processor command. And when I was writing my program the following happened. I wrote the following code :

#define PRINT_DEBUG_INFO(a) {cout << “Info: ” << a << endl;}
#include <iostream>

And no errors popped up.How is it possible to use cout before including iostream? Even if I declare the PRINT_DEBUG_INFO(a) without including iostream, I don't get a compiling error.
Can somebody explain me why this happens?

Upvotes: 7

Views: 2213

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

The preprocessor doesn't require any C++ declared symbols to be evaluated to do its work.

It's pure text processing, so defining a macro like

#define PRINT_DEBUG_INFO(a) {cout << “Info: ” << a << endl;}

and expanding it like

#include <iostream>

void foo {
  int a = 5;
  PRINT_DEBUG_INFO(a);
}

will become

// All the literal stuff appearing in <iostream>

void foo {
  int a = 5;
  {cout << “Info: ” << a << endl;};
}

So there's nothing checked regarding proper C++ syntax during definition or expansion of the macro.

These statements will be processed further by the C++ compiler, which will complain about cout isn't declared in the global scope.

To fix this, declare your macro like

#define PRINT_DEBUG_INFO(a) {std::cout << “Info: ” << a << std::endl;}

Upvotes: 27

Anthony Vinay
Anthony Vinay

Reputation: 647

You are just defining PRINT_DEBUG_INFO(a) and not using it. When you actually use it inside your program you will get the error that cout is not defined.

When you are not actually using it, the compiler finds no place to substitute the defined constant. When you actually use it, the program gets expanded during compilation and shows you the error.

And moreover there is a bracket in your macro which gets expanded with brackets and may lead to error.

Upvotes: 2

Ian Miller
Ian Miller

Reputation: 603

You define PRINT_DEBUG_INFO but you don't use it so there is nothing for the compiler to compile or complain about.

Upvotes: 3

Related Questions