C Macro for Sorting Two Integers: A Simple Example
Here's an example of a C macro that sorts two integers:
#include <stdio.h>
#define SWAP(a, b) do { \
int temp = a; \
a = b; \
b = temp; \
} while (0)
#define SORT(a, b) do { \
if (a > b) { \
SWAP(a, b); \
} \
} while (0)
int main() {
int x = 5;
int y = 3;
printf('Before sorting: x = %d, y = %d\n', x, y);
SORT(x, y);
printf('After sorting: x = %d, y = %d\n', x, y);
return 0;
}
In this example, the SWAP macro is defined to swap the values of two variables a and b. The SORT macro uses the SWAP macro to sort the values of a and b in ascending order.
The do { ... } while (0) construct is used to ensure that the macro behaves like a single statement, allowing it to be used within control flow structures like if statements.
In the main function, we demonstrate the usage of the SORT macro by sorting the values of x and y. The output of the program should be:
Before sorting: x = 5, y = 3
After sorting: x = 3, y = 5
原文地址: https://www.cveoy.top/t/topic/Ntn 著作权归作者所有。请勿转载和采集!