0

I wrote the following code to test MACRO functions:

#define err_exit(a, b) {fprintf(stdout,"%s\n",(a)); return (b); }

int func1(int a){
    if(a<50)
        err_exit("less than 50", a);
    if(a>50)
        err_exit("greater than 50", a);

    return 0;
}

int main() {
    fprintf(stdout, "\npop\n%d\n",func1(30));
    return 0;
}

And the output is:

less than 50

pop
30

But I was expecting this output:

pop
less than 50
30

Why is the text appearing before the pop? the function func1() is called after it!

How do macro replace instructions in the main code?

4

1 回答 1

2

First, func1(30) is called, so that it can be executed, and the result should be produced. The fprint() in main() needs that result, so that it can print its stuff.

As func1(30) gets executed, the fprintf() of the macro gets executed, and "less than 50" gets printed. Now, the result of func1(30) is available.

fprint() of main() can proceed with the printing now (since it has everything it needs (i.e. the result of func1(30)).

It will print "pop", and then "30", as expected.

于 2018-12-11T07:34:54.600 回答