13,454,623 members (55,698 online)
See more:
```#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;
}```

why it is not allowing int to be declared?can we declare inside a paranthesis?whether it is allowed?
Posted 17-Jan-13 1:52am

## Solution 2

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

I inserted a space, and exchanged parentheses for braces.
v2
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)
SWAP(x,y,int);
else
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 :)

## Solution 3

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)
SWAP(x,y,int);
else
y++;

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

Best regards
Espen Harlinn
v2
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

5.
Espen Harlinn 18-Jan-13 11:37am

Thank you, Carlo :-D

## Solution 4

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.

## Solution 1

Take a look Click[^]

Top Experts
Last 24hrsThis month
 CPallini 315 Maciej Los 303 John Simmons / outlaw programmer 289 OriginalGriff 235 Jochen Arndt 170
 OriginalGriff 5,495 Maciej Los 3,075 Richard Deeming 2,065 CPallini 2,062 Jochen Arndt 1,795