Macros vs Functions

Macros are preprocessed, meaning that all the macros would be executed before 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:

 

#define  A 10

int main()

{

     printf("%d",A);

     return 0;

}

 

int A()

{

    return 10;

}

int main()

{

    printf("%d", A());

    return 0;

}

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

MACRO

FUNCTION

Macro is Preprocessed

 

Function is Compiled

No Type Checking is done in Macro

Type Checking is Done in Function

Using Macro increases the code length

Using Function keeps the code length unaffected

Use of macro can lead to side effect at later stages

Functions do not lead to any side effect in any case

Speed of Execution using Macro is Faster

Speed of Execution using Function is Slower

Before Compilation, macro name is replaced by macro value

During function call, transfer of control takes place

Macros are useful when small code is repeated many times

Functions are useful when large code is to be written

Macro does not check any Compile-Time Errors

Function checks Compile-Time Errors

powered by social2s