bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / assignment-secondary / assignment-s-07.c

assignment-s-07.c (1252B)


      1 /* Write a program to swap two numbers using a macro (#define). */
      2 
      3 // IMPOSSIBLE
      4 /* It is impossible to swap two literal numbers defined using the 
      5 preprocessor directive #define. This is because #define performs simple 
      6 text substitution and does not create variables in memory that can be 
      7 manipulated or pointed to. */
      8 
      9 // Using a Function-Like Macro
     10 
     11 #include <stdio.h>
     12 
     13 // Define the SWAP macro.
     14 // The do-while(0) block is a common trick to ensure the macro behaves
     15 // like a single statement, regardless of where it is used (e.g., inside an 'if' statement).
     16 #define SWAP(a, b, data_type)   \
     17     do {                        \
     18         data_type temp = a;     \
     19         a = b;                  \
     20         b = temp;               \
     21     } while(0)
     22 
     23 int main() {
     24     int num1 = 15;
     25     int num2 = 42;
     26 
     27     printf("--- Before Swap ---\n");
     28     printf("Number 1 (num1): %d\n", num1);
     29     printf("Number 2 (num2): %d\n", num2);
     30 
     31     // Call the macro, passing the variables and their type
     32     // The preprocessor replaces this line with the block of code defined above.
     33     SWAP(num1, num2, int);
     34 
     35     printf("\n--- After Swap (using macro) ---\n");
     36     printf("Number 1 (num1): %d\n", num1);
     37     printf("Number 2 (num2): %d\n", num2);
     38 
     39     return 0;
     40 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror