0
0
Cprogramming~5 mins

Macro with arguments

Choose your learning style9 modes available
Introduction

Macros with arguments let you create reusable code pieces that work like small functions but run faster because they replace code directly.

When you want to reuse a small piece of code with different values.
When you need simple calculations or operations done quickly without function call overhead.
When you want to write code that works for different data without repeating it.
When you want to make your code easier to read by naming common operations.
When you want to avoid writing the same code multiple times with slight changes.
Syntax
C
#define MACRO_NAME(argument1, argument2, ...) (expression using arguments)

Macros are replaced by the preprocessor before the program runs.

Arguments in macros are like placeholders that get replaced with actual values.

Examples
This macro calculates the square of a number.
C
#define SQUARE(x) ((x) * (x))
This macro returns the bigger of two values.
C
#define MAX(a, b) ((a) > (b) ? (a) : (b))
This macro adds two numbers.
C
#define ADD(x, y) ((x) + (y))
Sample Program

This program uses a macro with arguments to multiply two numbers and print the result.

C
#include <stdio.h>

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

int main() {
    int x = 5;
    int y = 3;
    int result = MULTIPLY(x, y);
    printf("%d times %d is %d\n", x, y, result);
    return 0;
}
OutputSuccess
Important Notes

Always use parentheses around macro arguments and the whole expression to avoid unexpected results.

Macros do not check types, so be careful with side effects like incrementing variables inside arguments.

Macros are replaced before compilation, so debugging can be harder than with functions.

Summary

Macros with arguments let you write reusable code snippets that work like simple functions.

They are replaced directly in your code before it runs, making them fast but sometimes tricky.

Use parentheses carefully to avoid mistakes in calculations.