-1

I can't understand those macros in c++... I have heard from many videos and people that their job is to replace their name with something that you have defined them. For example:

#include <iostream>
#define say std::cout<<

int main()
{
    say "Hello World";
}

But I have seen many codes that do that

#include <iostream>
#define say

If you don't understand what I am saying they skip the second part of the definition...why?

1 Answers1

1

The statement #define say std::cout<< is a macro. macro name is say and macro body is std::cout<<. so when preprocessor will see the macro name it replaces with macro body.

At preprocessor stage your code looks like this

int main() {
 std::cout<< "Hello World";
 return 0;
}

just run g++ -Wall -E test.cpp and check yourself.

Case 2 : #define say

Here there is no macro body so it replaces with nothing. At preprocessor stage your code looks like this

int main() {
 "Hello World";
 return 0;
}
Achal
  • 11,821
  • 2
  • 15
  • 37
  • Might want to add to your answer the other part of his question, where he asks what `#define say` alone means. – Carl Apr 15 '18 at 17:33
  • that means there is no macro-body so it replaces with white-spaces I think. – Achal Apr 15 '18 at 17:38
  • 2
    The second case is commonly used so you can test it with an `#ifdef`. –  Apr 15 '18 at 17:39
  • yes I agree @NeilButterworth to check if `macro` is defined or not, use `#ifdef` – Achal Apr 15 '18 at 17:40