Skip to content

Commit 7076a4f

Browse files
committed
revise answer
1 parent 0f3101b commit 7076a4f

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

chapter04/4-14.c

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,45 @@
11
/*
22
* Exercise 4-14. Define a macro swap(t, x, y) that interchanges two arguments
33
* of type t. (Block structure will help).
4+
*
45
* By Faisal Saadatmand
56
*/
67

78
#include <stdio.h>
89

9-
#define SWAP(t, x, y) if (sizeof(x) == sizeof(t) && sizeof(y) == sizeof(t)) \
10-
{t temp = (x); temp = (x), (x) = (y), (y) = temp;}
10+
#define SWAP(t, x, y) if (sizeof((x)) == sizeof(t) && sizeof((y)) == sizeof(t)) \
11+
{t temp = ((x)); ((x)) = ((y)), ((y)) = temp;}
1112

12-
/* simpler but no type check */
13-
/*
14-
#define SWAP(t, x, y) if (x != y) {t temp = (x); temp = (x), (x) = (y), (y) = temp;}
15-
*/
16-
17-
/* alternatively we can use bitwise XOR, though it is considered bad practice */
18-
/*
19-
#define SWAP(t, x, y) if (sizeof(x) == sizeof(t) && sizeof(y) == sizeof(t)) \
20-
{(x) ^= (y), (y) ^= (x), (x) ^= (y);}
13+
/*
14+
* Alternatively we could use bitwise XOR for the swap, but it is considered
15+
* bad practice.
16+
*
17+
* #define SWAP(t, x, y) if (sizeof((x)) == sizeof(t) && sizeof((y)) == sizeof(t)) \
18+
* {(x) ^= (y), (y) ^= (x), (x) ^= (y);}
2119
*/
2220

2321
int main(void)
2422
{
25-
int a = 6;
26-
int b = 3;
23+
int a = 6, b = 3;
24+
char c = 99; /* 'c' */
25+
float f = 42.0f ;
26+
long int l = 25;
2727

28-
printf("Before SWAP a = %i b = %i\n", a, b);
28+
printf("int and int: types match\n");
29+
printf("Before SWAP\n a = %i b = %i\n", a, b);
30+
SWAP(int, a, b);
31+
printf("After Swap\n a = %i b = %i\n", a, b);
2932

33+
printf("\nchar and float: types don't match\n");
34+
printf("Before SWAP\n a = %c b = %2f\n", c, f);
3035
SWAP(int, a, b);
36+
printf("After Swap\n a = %c b = %2f\n", c, f);
3137

32-
printf("After Swap a = %i b = %i\n", a, b);
38+
printf("\nlong and int: types don't match,\
39+
but implicit conversion takes place\n");
40+
printf("Before SWAP\n a = %i b = %li\n", a, l);
41+
SWAP(int, a, b);
42+
printf("After Swap\n a = %i b = %li\n", a, l);
3343

3444
return 0;
3545
}

0 commit comments

Comments
 (0)