Macros vs Functions in C

Macros and functions are two different mechanisms in C for code reuse, but they work fundamentally differently. Macros are preprocessed before compilation, meaning they are textually replaced in the code. Functions are compiled as separate code blocks that are called during execution.

Syntax

#define MACRO_NAME(parameters) replacement_text

return_type function_name(parameters) {
    // function body
    return value;
}

Example: Macro vs Function Problem

This example demonstrates a common issue where macros and functions produce different results due to the way macros expand −

#include <stdio.h>

#define SQUARE(x) x * x

int sqr(int x) {
    return x * x;
}

int main() {
    printf("Use of sqr(). The value of sqr(3+2): %d<br>", sqr(3+2));
    printf("Use of SQUARE(). The value of SQUARE(3+2): %d<br>", SQUARE(3+2));
    return 0;
}
Use of sqr(). The value of sqr(3+2): 25
Use of SQUARE(). The value of SQUARE(3+2): 11

The function evaluates 3+2 to 5, then calculates 5 * 5 = 25. The macro expands SQUARE(3+2) to 3+2 * 3+2, which evaluates as 3 + (2 * 3) + 2 = 11 due to operator precedence.

Comparison

Aspect Macros Functions
Processing Preprocessed (text replacement) Compiled
Type Checking No type checking Strict type checking
Execution Speed Faster (no function call overhead) Slower (function call overhead)
Code Size Increases (code duplication) Constant (single copy)
Debugging Difficult to debug Easy to debug

Key Limitations of Macros

  • No type checking − Can cause unexpected behavior with different data types
  • Difficult debugging − Debugger sees expanded code, not original macro
  • No namespace − Macros are global and can cause name conflicts
  • Code bloat − Each macro usage duplicates the replacement text
  • No compile-time error checking − Errors only appear after expansion

Conclusion

While macros offer performance benefits due to no function call overhead, functions provide type safety, easier debugging, and better code maintainability. Use macros sparingly and prefer functions for most coding scenarios.

Updated on: 2026-03-15T10:29:40+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements