0
0
Cprogramming~5 mins

Define macro - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Define macro
O(1)
Understanding Time Complexity

Let's see how using a macro affects the time it takes for a program to run.

We want to know how the program's steps grow when using a macro.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

#include <stdio.h>
#define SQUARE(x) ((x) * (x))

int main() {
    int n = 5;
    int result = SQUARE(n);
    printf("%d\n", result);
    return 0;
}

This code defines a macro to square a number and uses it once.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single multiplication done by the macro.
  • How many times: Exactly once in this example.
How Execution Grows With Input

Since the macro just replaces code, the number of operations stays the same no matter the input size.

Input Size (n)Approx. Operations
101 multiplication
1001 multiplication
10001 multiplication

Pattern observation: The work does not increase with input size here.

Final Time Complexity

Time Complexity: O(1)

This means the program does a fixed amount of work regardless of input size.

Common Mistake

[X] Wrong: "Macros slow down the program because they add extra steps at runtime."

[OK] Correct: Macros are replaced before running, so they don't add runtime steps themselves.

Interview Connect

Understanding how macros work helps you explain how code runs efficiently and how compile-time changes affect runtime.

Self-Check

What if we used the macro inside a loop that runs n times? How would the time complexity change?