Macros vs Function in c

Macros vs Function in C



Macros are pre-processed which means that all the macros would be processed before your program compiles. However, functions are not pre-processed but compiled.

Examples of macros:-

#include<stdio.h>
#define String "Ritik"
int main()
{
printf("%s",String);
return 0;
}
output:-
Ritik

See the following example of Function:-

#include<stdio.h>
int n()
{
return 10;
}
int main()
{
printf("%d",n());
}
output:-
10

In macros, no type checking(incompatible operand, etc.) is done and thus use of micros can lead to errors/side-effects in some cases. However, this is not the case with functions. Also, macros do not check for compilation error (if any). Consider the following two codes:

Example:- Macros

#include<stdio.h>
#define SQUARE(a) a*a
int main()
{
printf("%d",SQUARE(2+3));
return 0;
}
output:-
11
 Example :- Functions 

#include<stdio.h>
int Square(int a){
    return a*a;
}
int main()
{
    printf("%d",Square(2+3));
    return 0;
}
output:-
25 
  • Macros are usually one liner. However, they can consist of more than one line, 
  • The speed at which macros and functions differs. Macros are typically faster than functions as they don’t involve actual function call overhead.
Macros:-
  • Macro is Pre-processed.
  • No Type Checking is done in Macro.
  • Using Macro increases the code length.
  • Speed of Execution using Macro is Faster
  • Macro does not check any Compile-Time Errors
Functions:-

  • Function Complied.
  • Type Checking is Done in Function.
  • Using Function keeps the code length unaffected.
  • Speed of Execution using Function is Slower.

Comments

  1. Thank you:-Neeta Borse ji for sharing your views and we will sure focus on the topics that you have suggested.
    Regards with team:-Codingriders

    ReplyDelete

Post a Comment