|
1 | 1 | /*
|
2 | 2 | * Exercise 4-14. Define a macro swap(t, x, y) that interchanges two arguments
|
3 | 3 | * of type t. (Block structure will help).
|
| 4 | + * |
4 | 5 | * By Faisal Saadatmand
|
5 | 6 | */
|
6 | 7 |
|
7 | 8 | #include <stdio.h>
|
8 | 9 |
|
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;} |
11 | 12 |
|
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);} |
21 | 19 | */
|
22 | 20 |
|
23 | 21 | int main(void)
|
24 | 22 | {
|
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; |
27 | 27 |
|
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); |
29 | 32 |
|
| 33 | + printf("\nchar and float: types don't match\n"); |
| 34 | + printf("Before SWAP\n a = %c b = %2f\n", c, f); |
30 | 35 | SWAP(int, a, b);
|
| 36 | + printf("After Swap\n a = %c b = %2f\n", c, f); |
31 | 37 |
|
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); |
33 | 43 |
|
34 | 44 | return 0;
|
35 | 45 | }
|
0 commit comments