Preprocessor Directives and the Build Process

Defining Macros with Arguments

How can I define a macro that takes arguments in C++?

Abstract art representing computer programming

You can define macros with arguments using the #define directive. Here's an example:

#include <iostream>

#define MULTIPLY(a, b) ((a) * (b))

int main() {
  std::cout << MULTIPLY(3, 4) << "\n";
  std::cout << MULTIPLY(2 + 3, 4 + 5) << "\n";
}
12
45

When defining macros with arguments, it's important to surround the arguments with parentheses to ensure proper precedence. This prevents unexpected behavior when the macro is expanded with complex expressions as arguments.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved