Working of the compiler directive in C++

192 views Asked by At

The #define compiler directive seems rather strange to me. I have read that no memory is allocated to it .

#include <iostream>
#define test 50
int main()
{
    cout<<test;
   return 0;
}

The above function displays 50 even though no memory is allocated to the compiler directive #define

How does compiler know that 50 is stored in it (test) without having any memory.

2

There are 2 answers

1
Stefan Falk On BEST ANSWER

Macros are not the same thing as variables.

Your compiler will translate the program

#include <iostream>
#define test 50
int main()
{
   cout << test;
   return 0;
}

to

#include <iostream>
int main()
{
   cout << 50;
   return 0;
}

by replacing the name test by its value given at your #define statement. You might want to take a look at some tutorials you can find on the internet e.g.:

#define getmax(a,b) ((a)>(b)?(a):(b))

This would replace any occurrence of getmax followed by two arguments by the replacement expression, but also replacing each argument by its identifier, exactly as you would expect if it was a function:

// function macro
#include <iostream>
using namespace std;

#define getmax(a,b) ((a)>(b)?(a):(b))

int main()
{
  int x=5, y;
  y= getmax(x,2);
  cout << y << endl;
  cout << getmax(7,x) << endl;
  return 0;
}
0
splrs On

Effectively, test is going to be replaced by 50 whereever it's encountered in the code prior to compilation. Because the replacement's not done at runtime there's no overhead.