#define directive use ?

What exactly are the benefits of using #define directives like this :
#include<stdio.h>
#define QUICK(x) printf("%s\n",x);
#define ADD(x, y) printf("%d\n",x+y);

int main()
{
QUICK(“Hello!”)
ADD(5,6)
return 0;
}

There are many overheads involved in the function call in C:

  1. First the address of the statement after the function call is stored.

  2. The instructions occupy a separate memory location.

  3. Then the arguments are pushed onto the function call stack.

  4. The statements are executed step by step.

  5. Then the control returns back to the address that was stored in the beginning.

I might be missing a few steps in this process of function call but the point to note is that there are a lot of overheads involved in the function call. These overheads might differ from language to language and sometimes from compiler to compiler.



Now consider a macro:

#define Max(x,y)((x>y)?(x):(y))

And the function for the same:

int max(int x,int y)

{return (x>y)?x:y;

}

When we use the function as a macro, it simply replaces the occurence of Max in the program at the compile time by the definition. Meaning there are no overheads like in the case of a function call.
It simply replaces the code. Thereby saving us from the overheads.

2 Likes

Besides reducing the overhead of function calls , one of the main reason is that macros make it possible to code faster (though code becomes tougher to understand and debug). Instead of writing printf("%d\n",x); everytime i have defined a macro define pi(x) printf("%s\n",x); so i just use pi(n) whenever i want to print which improves speed. This helps especially in short contests like Cook-Offs which rank users on submission time.

Most coders have a pre-defined set of macros which they use every time and with time and practice , coding speed improves. Here is a link to my solution with all pre-defined macros.

1 Like

The main advantage between a function and a macro is that macro or these #define things are faster than the functions. Because wen a function is called then the present position of the programme is stored (called the programme counter) is stored in a stack and it jumbs to the function call’s place. So it will take some amount of time for the function when it is used. But in the case of a macro is it actually a type of function where the code in the #define gets replaced in the source code when the programme is compiled. So this will be faster.:slight_smile: As @kcahdog has said many top coders use a coding template in which they will add such macros so that they can type and finish the programme in short period so that you can increase your rating :slight_smile:

Happy Coding

//