Click here to Skip to main content
15,506,209 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
#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;

why it is not allowing int to be declared?can we declare inside a paranthesis?whether it is allowed?

Try this instead

#define SWAP(a, b, c) {c t; t=a, a=b, b=t;}

I inserted a space, and exchanged parentheses for braces.
Share this answer
nv3 17-Jan-13 8:12am    
The space should not be necessary. Other than that you hit it!

To questioner: See the std::swap template function which does exactly that without even needing the type argument.
Espen Harlinn 17-Jan-13 8:39am    
What happens if your macro is used in this fashion:
if(x < y)
// Hint: It will not compile ...
Mattias Högström 17-Jan-13 11:05am    
You are right.
Hey!! Don't call it my macro. I just tried to correct it (but missed making it foolproof).
I hate macros. They are error prone and makes it harder to debug the code.
I would prefer an inlined function over a macro.

std::swap is the preferred alternative

ps. According to my coding style guideline
Even 1 line if else statements should use braces. :)
Espen Harlinn 17-Jan-13 14:41pm    
Relax, IMHO this should not be implemented as a macro :)

Use std::swap[^]
or if you're set on doing this using the preprocessor:
#define SWAP(a,b,c) do {c t=a; a=b; b=t;}while(0)

The do while construct ensures that you can do something like this:
if(x < y)
// rest of your code

Without undesired side effects - I would advice you to use std::swap.

Best regards
Espen Harlinn
Share this answer
H.Brydon 17-Jan-13 13:39pm    
Correct and complete... +5 from me.
Espen Harlinn 17-Jan-13 14:43pm    
Thank you, Brydon :-D
CPallini 18-Jan-13 7:41am    
I would advise the OP to follow your advice.
Espen Harlinn 18-Jan-13 11:37am    
Thank you, Carlo :-D
I am not sure where you are going with these questions, but I would strongly recommend you get hold of a decent book on C++ and study it. Trying to solve programming problems with preprocessor macros is a bad idea and can lead to many difficult to diagnose problems. Use the language to write your code using the proper tools and constructs.
Share this answer
Take a look Click[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900