You are here:

C++/macros in c++



Hello, Bill

what is the purpose of macros in c++?
and how can i use a macro from another file/program?


Macros are generally used for 2 purposes:

1.  To replace hard coded numbers with more meaningful and readable text.

If you have 5 products,


for( int index = 0; index < PRODUCT_COUNT; ++index )

is much more readable than

for( int index = 0; index < 5; ++index )

Also, if you add a product, you need only change the #define to 6 and not all of the occurrences of 5 to 6.

2.  To reduce a common expression to make the code more readable and with less to type.  However, in C++, depending on the use of the macro, a template may be a better choice since a template can be written to support the type used within the code.

For example:

#define IsLeapYear(year) ((year % 4) == 0)

Although it's simple, it can make the code more readable - we know what it's doing - ((year % 4) == 0) would need a comment just to clarify it.

[Note: This is not a full-blown leap year test as it works for years up to 2100 - good enough for most applications]



All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2017 All rights reserved.