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.
#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
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.