4

If I have two macros defined:

#define MAC1(X) {something here}
#define MAC2(X,Y) {something here}

and create a third one like this:

#define MAC3(X,Y) MAC1(X); MAC2(X,Y)

Can you please clarify how the MAC3 will be evaluated if called in the code?

Melebius
  • 6,183
  • 4
  • 39
  • 52
danny
  • 43
  • 1
  • 4
  • 2
    You can just run the preprocessor (e.g. `-E`), and see yourself. Note there's no double pass for the preprocessor, and it does only text replacement. – πάντα ῥεῖ May 12 '15 at 17:01
  • What isn't clear? You'll get the expansion of `MAC1` followed by the expansion of `MAC2`, just as one might expect. – Mike Seymour May 12 '15 at 17:01
  • @MikeSeymour, there is a smicolon at the end of MAC1, does it make any difference? – danny May 12 '15 at 17:11
  • @danny: Then you'll get a semicolon in the expansion, just as one might expect. – Mike Seymour May 12 '15 at 17:13
  • 2
    Look into "inline functions". Prefer functions to macros as [macros are evil.](http://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives) – Thomas Matthews May 12 '15 at 17:56

1 Answers1

8

If by the time you try to instantiate MAC3 both MAC1 and MAC2 are already declared, you will get

{something here}; {something here}

In other words, MAC1 and MAC2 will in turn get expanded.

If, however, MAC1 and MAC2 are declared after you use MAC3 (which is very unlikely), they won't get expanded.

Consider the following example:

#define A B
#define B 5

int main()
{
    printf("%d", A);
    return 0;
};

It will output 5, even though B is declared after A. What matters is that by the time you use A B is already declared.

Another important think to note in your example, that the X will get evaluated twice. For example, if you call MAC3 like that:

i = 0;
MAC3(i++, 1);

The value of i at the end will be 2 (assuming both MAC1 and MAC2 use X once).

Ishamael
  • 12,583
  • 4
  • 34
  • 52
  • sorry there is a semicolon at the end of MAC1, i wonder does it have any significance? – danny May 12 '15 at 17:10
  • 2
    No. #define's are expanded by a preprocessor that knows very little about the language itself. It just do string replacements. – Ishamael May 12 '15 at 17:11
  • 1
    actually it changes the behavior in loop statements as iv'e seen – danny May 13 '15 at 09:28