Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling multiple macros from another macro in C++

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?

like image 397
danny Avatar asked Feb 11 '23 04:02

danny


1 Answers

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).

like image 106
Ishamael Avatar answered Feb 13 '23 03:02

Ishamael