Defining Macros with Arguments

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

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.

Preprocessor Directives and the Build Process

Learn the fundamentals of the C++ build process, including the roles of the preprocessor, compiler, and linker.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

#ifdef vs #if defined()
What is the difference between #ifdef and #if defined() in C++?
Preventing Multiple Header Inclusion
What are the best practices to prevent multiple inclusion of header files?
Using #ifdef for Platform-Specific Code
How can I use #ifdef to write platform-specific code in C++?
Defining Constants with #define
Should I use #define to define constants in C++?
Using #pragma once in Header Files
What are the advantages of using #pragma once in header files?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant