Open In App

Importance of macros in C++

99.9%

of the C++ programs use macros. Unless you are making a basic file you have to write



#include

, which is a macro that pastes the text contained in a file. And it matters not the extension of the file. Macros are very powerful and can do things that not even



templates

,

lambdas

,

constexpr

,

inlining

or whatever future compiler constructs will ever do. The thing about the

CPP compiler

, and generally compilers, or the language, is that it is designed to restrict accidents. Such as using a type as another type, not setting object state before using object, not releasing memory, using a garbage value, in case of

java

– accessing out of bounds memory, etc etc. This is all fine and good, in fact errors get caught easier, but on the other hand, it restricts programmer from doing useful stuff. Then language creators end up having to devise means of getting around these restrictions. For example,

Java

has their

JNI

library for connecting to

C

and

C++

DLLs

. Problem is

Java

does not

have

macros

. Furthermore Java is a very verbatim language.




Java.util.something.member(.....

On the other hand,

C++ can use macros

for shorter names.




#define BIT64 (8)
#define TYPE std::conditional<size of(int) == BIT64, int, short>::type
#define TRUE (std::is_same<TYPE, int>::value)
#define TRY_ENABLE std::enable_if<TRUE, TYPE>::type
 
TRY_ENABLE func(){};
 
#undef // every definition

These illustrate many uses of macros:

So,

macros

not only make names shorter, and infact

typedefs

and

ref alias

can also be used to make names shorter, but macros can also avoid

runtime overheads

. Macros happen way before runtime. Macros have been avoiding run time over heads way before

CPP

features

such as

move

and

template

.


Article Tags :