Macro definitions

From Curuxa

In many programming languages, macro definitions (also known as defines or simply macros) are rules or patterns that specify how a certain input sequence should be mapped to an output sequence according to a defined procedure. This means that we can define some words and make them be transformed automatically to another word or sentence by the compiler, letting us perform common, difficult or repetitive tasks in a simpler way while writing our own programs.

They are used, for example, to define simpler names to the available variable types, or to access digital inputs/outputs with different names than the original ones.


How to make a definition (create a macro)

#define <identifier> <replacement token list>

Define a constant

#define PI 3.14159
float calculateCircumference(float radius) {
    return 2 * PI * radius;

Create an alias for a variable type

#define int8 char
unsigned char a = 28; //this is exactly the same as...
unsigned int8 a = 28;

Access a digital pin easily

#include <pic16fxxx.h>
#define Button RB3
#define Pressed 0
#define Released
void main() {
    // (setup here the microcontroller...)
    // ...
    if(Button == Pressed) {
        // do something...
    } else {
        // do something else...

See also