Joe
Joe

Reputation: 31

Using a variable inside a Macro in C++

I have come across the following Macro and I cannot understand what it's doing exactly;

#include <iostream>
#define TEST(a1) \
  int a1 = 5; 

int main(){

   TEST(a1);
   std::cout << a1  << std::endl;

   return 0;
}

It compiles and prints 5.

I know macros to a degree but I cannot wrap my head around what is happening here. To me TEST looks like a function which is redefining its argument a1?

Upvotes: 1

Views: 292

Answers (1)

user10957435
user10957435

Reputation:

A macro just puts the code defined in the macro wherever you call the macro through the preprocessor

What it basically comes down to is that this code:

#include <iostream>
#define TEST(a1) \
  int a1 = 5; 

int main(){

   TEST(a1);
   std::cout << a1  << std::endl;

   return 0;
}

becomes this code:

#include <iostream>

int main(){

   int a1 = 5; 
   std::cout << a1  << std::endl;

   return 0;
}

in effect.

The advantage to a macro, is that you can use it multiple times. And, since our example is parameterized, we can use it with minor variations. So, for example, this code:

#include <iostream>
#define TEST(a1) \
  int a1 = 5; 

int main(){

   TEST(a1);
   std::cout << a1  << std::endl;

   TEST(a2);
   std::cout << a2  << std::endl;

   TEST(a3);
   std::cout << a3  << std::endl;

   return 0;
}

becomes:

#include <iostream>

int main(){

   int a1 = 5; 
   std::cout << a1  << std::endl;

   int a2 = 5; 
   std::cout << a2  << std::endl;

   int a3 = 5; 
   std::cout << a3  << std::endl;

   return 0;
}

There are lots of things you can do with macros, and I recommend you research them, but this will get you started.

EDIT: Also worth mentioning is that, if you wanted to, you could change this macro to:

#define TEST(a1,val) \
  int a1 = val; 

That way, you could control the initialization value independently if you like. So:

TEST(a4,8)

becomes:

int a4 = 8;

Upvotes: 2

Related Questions