C Programming - C Preprocessor - Discussion

Discussion Forum : C Preprocessor - Find Output of Program (Q.No. 7)
What will be the output of the program?
#define SWAP(a, b) int t; t=a, a=b, b=t;
int main()
    int a=10, b=12;
    SWAP(a, b);
    printf("a = %d, b = %d\n", a, b);
    return 0;
a = 10, b = 12
a = 12, b = 10
Error: Declaration not allowed in macro
Error: Undefined symbol 't'
Answer: Option

The macro SWAP(a, b) int t; t=a, a=b, b=t; swaps the value of the given two variable.

Step 1: int a=10, b=12; The variable a and b are declared as an integer type and initialized to 10, 12 respectively.

Step 2: SWAP(a, b);. Here the macro is substituted and it swaps the value to variable a and b.

Hence the output of the program is 12, 10.

8 comments Page 1 of 1.

Rutu said:   3 years ago
In the previous question, it's shown that t can't declare at the start. Then how it's showing output now? Explain please.

Vishwanath said:   7 years ago
But the we might have two semi colons as they have used a semicolon in main function after swap.

Chuck said:   1 decade ago
For multiple statement in macros we have to use \ or {}.

Manish Atri said:   1 decade ago

int main()
int a=10, b=12;
int t;
t=a, a=b, b=t;

printf("a = %d, b = %d\n", a, b);
return 0;

This program works fine.
t=a, a=b, b=t; is complete statement.

Saurav said:   1 decade ago
But! how can it accept commas (,) to seperate statements?

Rahuln said:   1 decade ago
Well when we define a macro, I know that that code is going to be replaced in program but when these macros are replaced doesn't it take new variable name as one of the reason we passing only variable values and not there references.

Wikiok said:   1 decade ago
Yes, because ( ) is a function parameter list or a cast, not a sub block. Try { } instead of ( ).

Vema said:   1 decade ago
If we write #define SWAP(a, b) (int t; t=a, a=b, b=t;) , it gives an error.

Post your comments here:

Your comments will be displayed after verification.