Home »
C programming language
Recommendation for defining a macro in C language
Learn: What is the macro in C/C++ language? Here I am writing some of the recommendations; you should keep in mind while defining a macro.
Example of Macros:
#define MAX 100
#define PI 2.14
Recommendations/rules to define a Macro
-
Macros are usually used for constants, so whenever you require a constant type value you should use macros to:
- Make execution fast - because Marcos expends at compile time not at rum time.
- Save memory - like variable, macros do not take spaces in the memory.
- Make easy for changes - Yes, instead of hard coded values macros are easy to change. Make change once, compile the program and it will affect all places where used.
- enerally Macros are written in uppercase letters- it’s just a recommendation not a rule, you should write Marco names in uppercase to differentiate with other objects.
- Macros contains three words 1) #define 2) Macro_Name and 3) value. There must be spaces between the words.
- There must not be trailing semicolon (;), that means you cannot use semicolon after the statement (so, remember this).
Examples on defining MACRO
Example 1 - Here we are defining two MACROS with integer and string value
#include <stdio.h>
#define MAX_TRY 10
#define CITY "New, Delhi"
int main()
{
printf("value of MAX_TRY: %d\n",MAX_TRY);
printf("value of CITY: %s\n",CITY);
return 0;
}
Output
value of MAX_TRY: 10
value of CITY: New, Delhi
Example 2 - Here we are replacing "printf" with "PRINT"
#include <stdio.h>
#define PRINT printf
int main()
{
PRINT("Hello world!\n");
PRINT("How are you?\n");
//we can also use printf
printf("Hey! this is printf\n");
return 0;
}
Output
Hello world!
How are you?
Hey! this is printf