Macros vs Functions

Macros are preprocessed, meaning that all the macros would be executed before the compilation stage. However, functions are not preprocessed but compiled.

Example of Macro:

#include<stdio.h>

#define  A 10

int main()

{

     printf(“%d”,A);

     return 0;

}

 OUTPUT=10;

Example of Function:

#include<stdio.h>

int A()

{

    return 10;

}

int main()

{

    printf(“%d”, A());

    return 0;

}

OUTPUT=10;

Now compile them using the command:

GCC –E file_name.c

This will give you the executable code as shown below:

#include<stdio.h>

#define  A 10

int main()

{

     printf(“%d”,A);

     return 0;

}

#include<stdio.h>

int A()

{

    return 10;

}

int main()

{

    printf(“%d”, A());

    return 0;

}

The first program shows that the macros are preprocessed while functions are not.

In macros, no type checking (incompatible operand, etc.) is done, and thus, the use of macros can lead to errors/side-effects in some cases. That is not the case with functions. Macros do not check for a compilation error.

Macros are usually one-liners. However, they can consist of more than one line, and there are no such constraints in functions.

The speed at which macros and functions differ. Macros are typically faster than functions as they don’t involve actual function call overhead.

MACROFUNCTION
Macro is Preprocessed Function is Compiled
No Type Checking is done in MacroType Checking is Done in Function
Using Macro increases the code lengthUsing Function keeps the code length unaffected
Use of macro can lead to side effects at later stagesFunctions do not lead to any side effects in any case
Speed of Execution using Macro is FasterSpeed of Execution using Function is Slower
Before Compilation, the macro name is replaced by macro valueDuring function call, transfer of control takes place
Macros are useful when small code is repeated many timesFunctions are useful when large code is to be written
Macro does not check any Compile-Time ErrorsFunction checks Compile-Time Errors

Enquire Now

Enquire Now

Enquire Now

Please Sign Up to Download

Please Sign Up to Download

Enquire Now

Please Sign Up to Download

Enquiry Form

Quick Enquiry