MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

#define to create functional MACROS

The #define directive in C is also used to create function-like macros, which allow you to define snippets of code that can be reused with different arguments. These macros are processed by the preprocessor before the actual compilation takes place, making them a powerful tool for code abstraction and reusability.

Syntax

#define MACRO_NAME(parameters) (code with parameters)

here, MACRO_NAME: The name of the macro, parameters: The list of parameters (if any) that the macro takes, code with parameters: The code that will be substituted wherever the macro is used.


Here’s a basic example of a function-like macro:

#define SQUARE(x) ((x) * (x)) #define MAX(a, b) ((a) > (b) ? (a) : (b))

here, SQUARE(x) computes the square of x, MAX(a, b) returns the larger of a and b.


You can use these macros in your code like functions:

int num = 5;
int result = SQUARE(num); // Expands to ((5) * (5)) -> 25 int max_val = MAX(10, 20); // Expands to ((10) > (20) ? (10) : (20)) -> 20

Benefits

  1. Code Reusability: Macros can encapsulate commonly used code patterns, making your code more modular and easier to manage.
  2. Performance: Since macros are expanded inline, there’s no function call overhead. This can be beneficial in performance-critical sections of code.
  3. Flexibility: Macros can accept parameters, allowing for more dynamic and flexible code than simple constants.


Drawbacks

  1. Lack of Type Safety: Macros do not perform type checking. This can lead to unexpected results if the macro is used with inappropriate types or if the arguments have side effects.
  2. Debugging Difficulty: Since macros are expanded by the preprocessor, debugging can be challenging because the actual code executed is not always visible in the source files.
  3. Potential for Side Effects: If arguments to a macro have side effects, such as increment operations, those side effects can occur multiple times.


Ques. Write a macro to display the string COBOL in the following fashion:

C

CO

COB

COBO

COBOL

COBOL

COBO

COB

CO

C

Sol.

#include <stdio.h>
// Macro to print a substring of "COBOL" #define PRINT_SUBSTRING(str, length) \ do { \ for (int i = 0; i < length; ++i) { \ putchar(str[i]); \ } \ putchar('\n'); \ } while (0) // Function to print the desired pattern void printPattern(const char *str) { int len = strlen(str); // Print the increasing part for (int i = 1; i <= len; ++i) { PRINT_SUBSTRING(str, i); } // Print the decreasing part for (int i = len; i > 0; --i) { PRINT_SUBSTRING(str, i); } } int main() { const char *str = "COBOL"; printPattern(str); return 0; }

This approach uses the PRINT_SUBSTRING macro to perform the actual substring printing and utilizes a function to handle the pattern logic.

Report an issue

Reporting: #define to create functional MACROS (topic)

Related Posts