C Programming - C Preprocessor - Discussion

7. 

What will be the output of the program?

#include<stdio.h>
#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]. a = 10, b = 12
[B]. a = 12, b = 10
[C]. Error: Declaration not allowed in macro
[D]. Error: Undefined symbol 't'

Answer: Option B

Explanation:

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.


Vema said: (Sep 4, 2010)  
If we write #define SWAP(a, b) (int t; t=a, a=b, b=t;) , it gives an error.

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

Rahuln said: (Aug 29, 2011)  
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.

Saurav said: (Sep 5, 2011)  
But! how can it accept commas (,) to seperate statements?

Manish Atri said: (Jul 23, 2012)  
#include<stdio.h>

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.

Chuck said: (Sep 3, 2013)  
For multiple statement in macros we have to use \ or {}.

Vishwanath said: (May 17, 2017)  
But the we might have two semi colons as they have used a semicolon in main function after swap.

Rutu said: (Jul 25, 2021)  
In the previous question, it's shown that t can't declare at the start. Then how it's showing output now? Explain please.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.