assignment-s-07.c (1388B)
1 /* 2 * Author: Amit Dutta (amitdutta4255@gmail.com) | Date: 12 Dec 2025 3 * Repo: https://github.com/notamitgamer/bsc 4 * License: MIT 5 */ 6 7 /* Write a program to swap two numbers using a macro (#define). */ 8 9 // IMPOSSIBLE 10 /* It is impossible to swap two literal numbers defined using the 11 preprocessor directive #define. This is because #define performs simple 12 text substitution and does not create variables in memory that can be 13 manipulated or pointed to. */ 14 15 // Using a Function-Like Macro 16 17 #include <stdio.h> 18 19 // Define the SWAP macro. 20 // The do-while(0) block is a common trick to ensure the macro behaves 21 // like a single statement, regardless of where it is used (e.g., inside an 'if' statement). 22 #define SWAP(a, b, data_type) \ 23 do { \ 24 data_type temp = a; \ 25 a = b; \ 26 b = temp; \ 27 } while(0) 28 29 int main() { 30 int num1 = 15; 31 int num2 = 42; 32 33 printf("--- Before Swap ---\n"); 34 printf("Number 1 (num1): %d\n", num1); 35 printf("Number 2 (num2): %d\n", num2); 36 37 // Call the macro, passing the variables and their type 38 // The preprocessor replaces this line with the block of code defined above. 39 SWAP(num1, num2, int); 40 41 printf("\n--- After Swap (using macro) ---\n"); 42 printf("Number 1 (num1): %d\n", num1); 43 printf("Number 2 (num2): %d\n", num2); 44 45 return 0; 46 }