Function macro

I will explain about function macros. Function macros are pseudo-functions that the preprocessor expands before compilation.

#define Macro function name (argument 1, argument 2, ...) Processing content

Function macros have a very high risk of causing side effects, so use them first. We recommend that you do not.

However, in some cases you may not want to rely on the inline expansion of the compiler for the fastest tuning, and in other cases you may want to use function macros.

In such a case, you can reduce the side effects by surrounding the process with "do {} while (0)". In this case, the return value cannot be returned. In the macro function, you can rewrite the value directly, but if there is a value you want to change, it is recommended to pass it with a pointer to match the specifications of the C language function.

Function macro sample program

This is a sample that adds two numbers using a function macro. If the process spans multiple lines, escape the line breaks with "\".

#include <stdio.h>
#include <stdint.h>

// Definition of function macro
#define MYAPP_ADD (in1, in2, out_ptr) \
do {\
  * out_ptr = in1 + in2; \
} while (0) \

int main (void) {
  int32_t num1 = 3;
  int32_t num2 = 2;
  int32_t total = 0;
  // Use function macros
  MYAPP_ADD (num1, num2, & total);
  printf("%d\n", total);

Associated Information