hrishi007
hrishi007

Reputation: 133

Why are these macro definitions expanded so differently?

#define INC1(a) ((a)+1)

#define INC2 (a) ((a)+1)

#define INC3( a ) (( a ) + 1)

#define INC4 ( a ) (( a ) + 1)

for above declaration in C language INC1 and INC3 works fine but INC2 and INC4 gives error, why ?

reference : https://www.geeksforgeeks.org/c-quiz-110-gq/ First Question

Upvotes: 1

Views: 82

Answers (2)

Yunnosch
Yunnosch

Reputation: 26753

Please take this as an example-extension to the answer by Some programmer dude.

With your definitions, this piece of code...

INC1(10)
INC2(20)
INC3(30)
INC4(40)

will expand to ...

((10)+1)
(a) ((a)+1)(20)
(( 30 ) + 1)
( a ) (( a ) + 1)(40)

I guess now the question arises "Why is the presence of the whitespace so important?"
The answer to that is implied in an insightful way in the comment by Groo (I hope they permit me using and elaborating here.)

Assume that you actually want a macro to be expanded to something like ( a ) (( a ) + 1). How would you do that, if these two definitions were treated identically?

#define INC1(a) ((a)+1)
#define INC2 (a) ((a)+1)

And would be expanded to

((10)+1)
((20)+1)

The difference between

INC(x) ...
INC (x) ...

makes that possible in a kind-of-intuitive way. Once you are aware of the problem.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409266

The syntax of function-like macros requires the opening parentheses to follow directly after the macro name, without any space between.

The preprocessor uses the space after the macro name to deduce when the macro-name ends and the body of the macro begins.

For example:

#define INC2 (a) ((a)+1)

This defines a non function-like macro, which expands to (a) ((a)+1).

Upvotes: 4

Related Questions