0

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.

  • Macros perform a simple textual substitution at compile time. Everywhere "test" appears, the compiler substitutes "50". So the program works exactly the same as if you've written `cout<<50;` – Igor Tandetnik Dec 09 '14 at 16:14
  • Also, as this is C++ you should really be using `const int test = 50;`. We worked hard when standardizing C++ to make `#define` almost unnecessary. – kdopen Dec 09 '14 at 16:21

2 Answers2

5

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;
}
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
3

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.

splrs
  • 2,424
  • 2
  • 19
  • 29