EN VI

syntax of macro-like function in C?

2024-03-17 21:30:04
How to syntax of macro-like function in C

In the web, I read that to define a macro that behave like a function, the syntax is:

#define foo(x,y) (bar((x),(y)))

but considering that a macro is just text replacement, why is the syntax above used, and not just (bar(x,y)) or bar(x,y)?

If I write

#define add0(x,y) ((x)+(y))

#define add1(x,y) (x+y)

#define add2(x,y) x+y

All of the three macros output 3 when printed.

Solution:

The need for parentheses in macros in C

C macros and use of arguments in parentheses

Writing without parentheses can lead to unexpected operator precedence problems.

Consider the following example:

#define add2(x,y) x+y

If you call add2(1, 2) * 3, it would expand to 1 + 2 * 3, which is 7, not 9. This is because the multiplication operator has higher precedence than the addition operator in C and C++.

However, if you define the macro as:

#define add0(x,y) ((x)+(y))

It's fine now.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login