Multiline Macros In C

A multiline macro can be established through the #define preprocessor directive. Employ the backslash (/) symbol to signify that the macro definition extends to the next line after a line break. To define a multiline macro, adhere to the fundamental syntax below:

Example

#define MACRO_NAME \
    do { \
        // Multiline code here \
    } while(0)

In this instance, the MACRO_NAME represents the name of the macro, which consists of a do-while(0) construct enveloping the block of code. By employing the do-while(0) loop in the expansion of the macro, it serves to avoid issues related to semicolons, transforming the macro into a unified statement.

Using a Multiline Macro:

You can employ a multiline macro similarly to invoking a function by using its designated name. Here is a demonstration of how the MACRO_NAME macro could be implemented:

Example

int main() {
    // Other code
    MACRO_NAME;
    // Other code 
    return 0;
}

The code specified within the macro gets replaced with MACRO_NAME. This replacement is carried out by the preprocessor upon encountering this particular line.

Program-1:

Example

#include <stdio.h>
// Define a multiline macro named MACRO
#define MACRO(num, str) ({\
printf("%d", num);\
printf(" is");\
printf(" %s number", str);\
            printf("\n");\
           })
int main(void)
{
    int num;
    // Prompt the user to input a number
printf("Enter a number: ");
scanf("%d", &num);
    // Check if the number is odd or even
    if (num & 1) {
        // If odd, call the MACRO macro to print the result
printf("%d", num);
printf(" is");
printf(" %s number", "Odd");
        printf("\n");
    } else {
        // If even, call the MACRO macro to print the result
printf("%d", num);
printf(" is");
printf(" %s number", "Even");
        printf("\n");
    }
    return 0;
}

Output:

Output

Enter a number: 76
76 is Even number

Explanation:

  • The standard input-output library (stdio.h) is imported in this line, providing functions for input and output operations such as printf and scan.
  • Following that, a multiline macro named MACRO is declared. This macro takes two parameters: num, an integer, and str, a string. Within the macro, the number and its parity (odd or even) are displayed using multiple printf statements based on the provided string.

In the Main function:

  • The user input is specified as an integer variable named num .
  • The user is asked for a number using the printf function .
  • An integer is read from the user and stored in the num variable using the scanf
  • The program returns an exit status of 0, indicating successful execution, and the main function exits.
  • Complexity Analysis:

Time Complexity:

The printf and scanf functions exhibit a time complexity that decreases as the number of characters printed or read increases. Despite this, they are often considered to operate in constant time, O(1), due to the typically small and independent nature of the character count in relation to the input size.

Conditional Evaluation: The if (num & 1) statement employs a bitwise AND operation with a constant time complexity of O(1).

Printing: The function's complexity remains constant, denoted as O(1), as it contains a fixed quantity of printf statements within both the if and else conditions, unaffected by the input scale.

The code's total time complexity remains constant at O(1) as it does not rely on the size of the input.

Space Complexity:

Variables: The space complexity remains constant at O(1) as 'num' is a singular integer variable.

Temporary Storage: The scanf function requires a small and consistent amount of temporary storage (considered as constant, O(1)) for input buffering.

Function invocation: The overhead is necessary for the printf and scanf function invocations. Nonetheless, this expense is minimal and can be considered constant, O(1).

Constant space complexity (O(1)) characterizes the code. The variable 'num' and other data containers take up a consistent amount of memory. The memory utilized by the temporary storage for 'scanf' is minimal. The overhead associated with invoking functions like 'printf' and 'scanf' is relatively small. Conditional execution ('if' statements) introduces minimal memory fluctuations. Macro expansion requires only a small amount of memory, which is subsequently freed after expansion. Consequently, the size of the input does not affect memory consumption.

Program-2:

Example

#include <stdio.h>

#define SWAP(a, b) \
    do { \
        int temp = a; \
        a = b; \
        b = temp; \
    } while(0)
int main() {
    int x = 5, y = 10;
printf("Before swapping: x = %d, y = %d\n", x, y);
SWAP(x, y);
printf("After swapping: x = %d, y = %d\n", x, y);    
    return 0;
}

Output:

Output

Before swapping: x = 5, y = 10
After swapping: x = 10, y = 5

Explanation:

  • Here, we're creating the SWAP macro , which accepts the arguments a and b . This macro's goal is to change the values of two variables.
  • After that, the do-while(0) loop opens the macro. The macro can be used everywhere, and a single statement is anticipated by acting like a single statement with the help of the loop. The while(0) and do commands are used to execute the code.
  • A temporary variable named temp is set up inside the loop and given the value of a . During the swapping operation , the value of a is temporarily stored in this temporary variable.
  • After that, the value of b is given to the value of a.
  • To effectively swap the values of a and b, the value stored in the temp variable is assigned to the value of b.

In the Main function:

  • The initial values of the two integer variables x and y are 5 and 10 , respectively.
  • The x and y values before the swapping operation are printed using the printf function .
  • Invoking the SWAP macro with the inputs x and y effectively swaps their values.
  • After the swapping procedure, the printf function is again used to print the x and y values.

The SWAP macro simplifies the swapping operation by providing a convenient method to exchange the values of two variables without the need to manually declare a temporary variable and assign values each time explicitly.

Complexity Analysis:

Time Complexity:

  • Int x = 5 and Int y = 10 are declared and initialized with constant time complexity, O(1).
  • Printing: The O(1) constant time complexity of the printf function's request to print the x and y values before and after switching is used.
  • Swapping: The SWAP macro performs three straightforward assignments requiring constant time, or O(1) .
  • As a result, the code's overall time complexity is O(1) , which means that the execution time is independent of the input size.

Space Complexity:

  • The space complexity measures the program's memory usage. In the sample of code provided:
  • Declared variables x and y take up O(1) constant space complexity.
  • Temporary Variable: O(1) constant space is consumed by the temp variable utilized in the swapping operation.
  • Function Calls: The printf function calls take a tiny bit of memory for function call overhead, but the quantity is insignificant and can be regarded as constant, O(1) .
  • As a result, the code has a space complexity of O(1) , meaning it does not scale with the input size.
  • Benefits of Multiline Macro:

There are numerous advantages of using multiline macros in C programming. Some key benefits of multiline macros in C include:

Condensing intricate procedures or coding structures into a singular macro, multiline macros promote modularity and reusability within different parts of your program.

By providing a straightforward way to represent repetitive or boilerplate code, macros can aid in reducing code redundancy, leading to a more concise and sustainable codebase.

By detailing intricate or specific tasks within macros, you can ensure uniformity in functionality throughout your complete program, reducing the chances of mistakes stemming from irregular execution.

By utilizing macros with conditional logic, you have the ability to maintain a unified codebase across multiple scenarios. This allows for the toggling of features or the inclusion of platform-specific code as needed.

Challenges of Multiline Macro:

There are numerous difficulties associated with multiline macros in the C programming language. Some primary obstacles of multiline macros in C include:

Limited Expressiveness: While multiline macros can manage intricate code segments, their expressiveness is restricted compared to functions due to the requirement for local variables and proper scoping.

Maintainability: Overusing multiline macros can lead to code that is hard to comprehend, increasing the complexity of maintenance and debugging tasks.

Compilation Duration: Utilizing intricate macros that require expansion and regeneration can potentially lead to longer compilation times if they are used frequently.

Code Bloating: The executable size and performance might be affected by the expansion of macros multiple times within the program.

Input Required

This code uses input(). Please provide values below: