Macros are a part of code which is named and replaces the name with the code when invoked. The advantages of macros are
- It makes the code short and more readable
- Easy to edit the code
Macros can be used for declaring constants such as strings (as objects or constants) and integers and defining reused codes (just like functions).
Declaring constants
Macros are declared in the top part of the program, so it’s easy to declare and re-declare constants. One of the best example is crystal frequency declaration which is needed for inbuilt delay routines of XC8 compiler.
#define _XTAL_FREQ 20000000
Declaring function-like macros
By defining reused codes as function-like macros, one can efficiently make the code more readable and short. Advantages of this is the portability and readability by making it short in length and more human friendly.
An example for this idea is finding minimum and maximum from two numbers. One can easily define these using Macros.
#define MAX(a,b) a>b?a:b #define MIN(a,b) a<b?a:b
It can be used in programs by replacing a and b with numbers.