1,175 views
3 votes
3 votes
#include<stdio.h>
#define SWAP(a, b, c)(c t; t=a, a=b, b=t)
int main()
{
    int x=10, y=20;
    SWAP(x, y, int);
    printf("%d %d\n", x, y);
    return 0;
}

1 Answer

0 votes
0 votes
After Macro expansion it will look similar like this



#include<stdio.h>
#define SWAP(a, b, c)(c t; t=a, a=b, b=t)
int main()
{
    int x=10, y=20;
    (int t; t=x, x=y, y=t);
    printf("%d %d\n", x, y);
    return 0;
}

Let's see where things go wrong as the code isn't compiling.

(int t; t=x, x=y, y=t);

This line will give an error, as we can have only a single statement inside (). 

Here we have multiple statement int t; // ; indicates end of a statement

Let's try to modify the code.

#include<stdio.h>
#define SWAP(a, b, c) c t; t=a, a=b, b=t
int main()
{
    int x=10, y=20;
    SWAP(x, y, int); // expanded as int t; t=a, a=b, b=t;
    printf("%d %d\n", x, y);
    return 0;
}

This will work without error. 

Related questions

0 votes
0 votes
0 answers
2
0 votes
0 votes
1 answer
3