VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-macros/

⇱ Macros In C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Macros In C++

Last Updated : 26 Aug, 2025

Macros are shortcuts or placeholders that the preprocessor replaces before the code is compiled. They are defined using #define and can be used to create constants or code snippets.

Syntax

  • MACRO_NAME: It is the name we give to the macro, that's usually in uppercase to differentiate it from ordinary C++ identifiers.
  • macro_definition: It is the code that the preprocessor will substitute whenever the macro is used.

Example:


Output
Square of 7 is 49

Types of Macros in C++

Macros can be classified into four types in C++:

  1. Object-Like Macros
  2. Function-Like Macros
  3. Conditional Macros

1. Object-Like Macros

These are used to define constant values — like replacing a word with a fixed number or text.

Example:

In this example, PI is defined as an object-like macro, and whenever PI appears in the code, it is replaced with the value 3.14159.


Output
Area of circle with radius 4 is 50.2654

2. Function-Like Macros

These macros look like functions, but they are just text replacements.

Example:

In this example, PRINT(x) is a function-like macro that takes an argument x and expands to a function that prints the value of x.


Output
Value is: 42

3. Conditional Macros (for Conditional Compilation)

These are used to control which parts of the code should be compiled, based on whether something is defined or not.

Example:


Output
[DEBUG] x = 5
[DEBUG] y = 10
[DEBUG] sum = 15
Sum: 15

Predefined Macros

Predefined macros are special macros that are already built into the C++ compiler.
You don't need to define them — they are automatically available in your program.

The following are some commonly used predefined macros in C++:

  1. __LINE__: This macro expands to the current line number in the source code.
  2. __FILE__: This macro expands to the name of the current source file.
  3. __DATE__: This macro expands to a string that represents the date of compilation.
  4. __TIME__: This macro expands to a string that represents the time of compilation.

Example

In this example, __LINE__ is replaced with the current line number, __FILE__ with the source file name and __DATE__ with the compilation date. These can be handy for debugging and logging.


Output
This is line 10 in file ./Solution.cpp
Compiled on Nov 7 2023

Advantages of Macros

  1. Macros lets us reuse code without rewriting it.
  2. Macros allow easy updates
  3. Macros can control which code is included during compilation

Disadvantages of Macros

  1. Macros can cause bugs as they don't do type checking.
  2. Macros can lead to unexpected behavior.
  3. Macros increase code complexity.


Comment