Difference Between Macro and Function in C

1. Introduction

In C programming, macros and functions are both tools for code reuse, but they operate in fundamentally different ways. A macro is a preprocessor directive that represents a piece of code that is replaced by the macro's value before the program is compiled. Functions, on the other hand, are blocks of code that perform a specific task and can be called with different parameters during program execution.

2. Key Points

1. Macros are handled by the preprocessor and are replaced before compilation.

2. Functions are compiled and executed during runtime.

3. Macros can improve performance by eliminating function call overhead but can lead to code bloat.

4. Functions provide modularity, reduce code redundancy, and can be debugged easily.

3. Differences

Macro Function
Replaced by the preprocessor before compilation. Executed during runtime.
No type checking is performed. Type checking is performed.
Can lead to unexpected errors if not used carefully. More reliable and easier to debug.

4. Example

#include <stdio.h>

// Macro example
#define SQUARE(x) ((x) * (x))

// Function example
int square(int x) {
    return x * x;
}

int main() {
    int value = 5;
    printf("Square using macro: %d\n", SQUARE(value));
    printf("Square using function: %d\n", square(value));
    return 0;
}

Output:

Square using macro: 25
Square using function: 25

Explanation:

1. The macro SQUARE is replaced by its definition during the preprocessing phase, so SQUARE(value) becomes ((5) * (5)).

2. The function square is called during runtime, and the value 5 is passed to it as an argument.

5. When to use?

- Use macros for small, repetitive tasks that can be defined in a single line to save function call overhead.

- Use functions for more complex tasks that require modularity, type checking, and ease of debugging.

Difference between malloc() and calloc()?

Difference between Local Variable and Global Variable in C

Difference between Global and Static Variables in C

Difference Between Call by Value and Call by Reference in C

Difference Between getch() and getche() in C

Difference between printf() and sprintf() in C

Difference between Arrays and Pointers in C

Difference between Structure and Union in C

Difference Between Stack and Heap Memory Allocation in C

Difference Between Macro and Function in C

Difference between = and == in C

Difference Between for loop and while loop in C

Difference Between Linked List and Array in C

Difference between fgets() and gets() in C

Difference between ++i and i++ in C

Difference between struct and typedef struct in C

Difference between int main() and void main() in C

Difference between Character Array and String in C

Difference between break and continue in C

Difference between exit() and return in C

Comments