C++ macros – All you need to get started!

Filed Under: C++
C MACROS

Hello, All! In this article, we will be focusing on an important aspect of system Programming — C++ macros. So, let us begin!


What is C++ macros?

Before jumping into macros, let us first understand the concept of Preprocessors in system programming.

Preprocessors assist the compilers and give instructions to preprocess certain commands before the compilation of the program begins! As the preprocessor directives are system programming statements, they do not end with a semicolon.

Macros is one such preprocessor directive. It can be considered as a piece of code, that has been assigned a name/label. So, whenever the compiler encounters this name, the compiler would replace the name with the entire piece of code assigned to the label/name.

This leads to the reusability of the code and saves a lot of time in terms of compilation.

Let us now focus on the structure of macros in the upcoming section.


Defining a macro in C++

Macros are defined using a #define directive in C++ programming. Have a look at the below syntax!

#define macro_name text/function

We specify a name to the macro which is the label for the entire text/function that the compiler will replace once it encounters the macro name.

So, during the execution of a program, all the macros will be replaced by the specified text/function before the compilation of the program.


Examples of C++ Macros

In the below example, we have defined a macro using the #define directive as shown below:

#include <iostream> 
using namespace std;
#define PI 3.14 //macro variable
int main() 
{ 
	float area = 0.0;
	int r = 2;
	area = PI*r*r;
	cout<<"Area of the circle: "<<area;
	return 0; 
} 

So, when the compiler encounters the macro-name i.e. ‘PI’, it replaces the macro-name with 3.14 before the compilation of the entire code.

Output:

Area of the circle: 12.56

Now, we have used a function as a replacement value for a macro as shown below.

#include <iostream> 
using namespace std;
#define PI 3.14
#define PERIMETER(r) (2*PI*r) //macro function
int main() 
{ 
	float peri_meter = 0.0;
	int r = 10;
	peri_meter = PERIMETER(r);
	cout<<"Perimeter of the circle: "<<peri_meter;

	return 0; 
} 


So, when the compiler encounters the macro-name ‘PERIMETER’, it replaces the macro with the function defined as the replacement value for it.

Output:

Perimeter of the circle: 62.8

Conclusion

By this, we have come to the end of this topic. Hope this article helps you to understand the concept of macros in a well versed manner!

Feel free to comment below, in case you come across any question.

Till then, Happy Learning!!


References

Macros in C++ — Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages