YouTip LogoYouTip

C Exercise Example48

# C Programming Classic 100 Examples: Exercise 48 ## Introduction In C programming, the `#define` preprocessor directive is a powerful tool used to define macros. Macros allow for text substitution before the actual compilation of the code begins. This exercise demonstrates how to use `#define` to create custom aliases for standard relational operators (`>`, `<`, and `==`). While this is an educational exercise to understand the mechanics of the preprocessor, it highlights the flexibility of C's macro substitution capabilities. --- ## Problem Description **Goal:** Write a C program that practices using the `#define` macro directive to replace relational operators with custom identifiers, and use them to compare two user-inputted integers. --- ## Code Implementation Below is the complete C source code. The comments have been translated into English for clarity. ```c /** * C Exercise Example 48 * Description: Macro #define practice part 3. */ #define LAG > #define SMA < #define EQ == #include int main() { int i, j; printf("Please enter two numbers:\n"); scanf("%d %d", &i, &j); // The preprocessor replaces LAG, EQ, and SMA with >, ==, and < respectively if (i LAG j) { printf("%d is greater than %d\n", i, j); } else if (i EQ j) { printf("%d is equal to %d\n", i, j); } else if (i SMA j) { printf("%d is less than %d\n", i, j); } else { printf("No valid relationship found.\n"); } return 0; } ``` --- ## Output Verification When you compile and run the program, it will prompt you to enter two integers. ### Example Run: ```text Please enter two numbers: 1 2 1 is less than 2 ``` --- ## Code Analysis & Technical Considerations ### How It Works During the preprocessing phase (before compilation), the C preprocessor scans the source code and performs direct text substitution based on the `#define` directives: * Every occurrence of the token `LAG` is replaced with `>`. * Every occurrence of the token `SMA` is replaced with `<`. * Every occurrence of the token `EQ` is replaced with `==`. Thus, the line `if(i LAG j)` is transformed into `if(i > j)` before the compiler compiles the code. ### Best Practices and Considerations While this exercise is excellent for understanding how the preprocessor works, you should keep the following in mind for real-world production code: 1. **Readability:** Replacing standard operators (like `<`, `>`, `==`) with custom macros is generally discouraged in professional software development. It makes the code harder to read and maintain for other developers who expect standard C syntax. 2. **No Type Checking:** Macros are simple text replacements and do not perform any type checking. 3. **Debugging Challenges:** Debugging code with heavily nested or non-standard macros can be difficult because the debugger references the post-processed code, which might look different from your original source code.
← C Exercise Example49C Exercise Example47 β†’