Macro

Is a fragment of code that has a name. Whenever the name is used, it is replaced by the content of the macro.

There are two type of macro:

  1. Object-like macro
  2. Function-like macro

Object-like macro

It's normally use to hold some data. For example:

#include <stdio.h>

#define BUFFER_SIZE 1024

int main() {
    printf("buffer size: %d\n", BUFFER_SIZE);
    return 0;
}
buffer size: 1024

There is no restriction in what you can put in macro

#include <stdio.h>

#define BUFFER_SIZE 1024
#define HELLO_WORD "hello world"
#define NUMBERS 1, 2, 3, 4, 5
#define FRACTION_CODE ; puts("hi hi")

int main() {
    printf("buffer size: %d\n", BUFFER_SIZE);
    
    char name[] = HELLO_WORD;
    puts(name);

    int array[] = { NUMBERS };
    printf("%d", array[2])FRACTION_CODE;


    return 0;
}
buffer size: 1024
hello world
3hi hi

Function-like macro

You put a parameter here and write the code that you want in that parameter.

It behaves similar like a function just replacing the code at that moment.

#include <stdio.h>

#define print_hello(name) printf("name: %s", name)

int main() {
    print_hello("xin chao");
}
name: xin chao

One use case is to Retrieve array length