C Programming Macros
Last modified by Microchip on 2023/11/09 09:06
Macros:
- Are evaluated by the preprocessor
- Are not executable code themselves
- Can control the generation of code before the compilation process
- Provide shortcuts
Simple Macros
Syntax
#define label text
- Every instance of label in the current file will be replaced by text
- text can be anything you can type into your editor
- Arithmetic expressions evaluated at compile time
Example
1 #define Fosc 4000000
2 #define Tcy (4 * (1/Fosc))
3 #define Setup InitSystem(Fosc, 250, 0x5A)
2 #define Tcy (4 * (1/Fosc))
3 #define Setup InitSystem(Fosc, 250, 0x5A)
Argument Macros
Syntax
#define label(arg1,…, argn) code
- The code must fit on a single line or use "\" to split lines
- Text substitution used to insert arguments into code
- Each instance of the label() will be expanded into code
- This is not the same as a C function
Example
1 #define min(x, y) ((x)<(y)?(x):(y))
2 #define square(x) ((x)*(x))
3 #define swap(x, y) { x ^= y; y ^= x; x ^= y; }
2 #define square(x) ((x)*(x))
3 #define swap(x, y) { x ^= y; y ^= x; x ^= y; }
Extreme care must be exercised when using macros. Consider the following use of the below macro:
1 #define square(a) ((a)*(a))
1 i = 5;
2 x = square(i++);
2 x = square(i++);
The result will be the following:
x = 30
i = 7
i = 7