سؤال

#include<stdio.h>
#define exch(A,B) {int t=A;A=B;B=t;}
int main(void)
{
    int a=1,b=4;
    exch(a,b);
    printf("%d\t%d\n",a,b);
    return 0;
}

Prints:a=4,b=1

In the output, a and b have been exchanged; why is a macro not call by value? Please help me by explaining the result.

هل كانت مفيدة؟

المحلول

Because macros are not functions, the preprocessor just replaces the text. After the macro substitution, your program turns into:

//code in stdio.h

int main(void)
{
    int a=1,b=4;
    {int t=A;A=B;B=t;}
    printf("%d\t%d\n",a,b);
    return 0;
}

See? There's no function calls in the swapping.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top