C Macro for Sorting Three Integers: A Comprehensive Guide
Here is an example of a C macro that can be used to sort three integers:
#include <stdio.h>
#define SWAP(a, b) do { \
int temp = a; \
a = b; \
b = temp; \
} while (0)
#define SORT3(a, b, c) do { \
if (a > b) { \
SWAP(a, b); \
} \
if (a > c) { \
SWAP(a, c); \
} \
if (b > c) { \
SWAP(b, c); \
} \
} while (0)
int main() {
int num1 = 3;
int num2 = 1;
int num3 = 2;
printf('Before sorting: %d, %d, %d\n', num1, num2, num3);
SORT3(num1, num2, num3);
printf('After sorting: %d, %d, %d\n', num1, num2, num3);
return 0;
}
This macro uses the SWAP macro to swap two integers if the first one is greater than the second one. Then, the SORT3 macro uses multiple conditional statements to sort the three integers in ascending order. Finally, the main function demonstrates the usage of the macro by sorting three integers and printing the results.
原文地址: https://www.cveoy.top/t/topic/Jui 著作权归作者所有。请勿转载和采集!