Macro Functions - C Preprocessor

C examples for Preprocessor:Macro

Introduction

A macro can take arguments.

For example, the following macro function gives the square of its argument.

#define SQUARE(x) ((x)*(x))

The macro function is called just as if it was a regular C function.

To use this kind of function, the arguments must be known at compile time.

int x = SQUARE(2); /* 4 */

The extra parentheses in the macro definition are used to avoid problems with operator precedence.

Example,

Demo Code

#define SQUARE(x) x*x/*www.ja v a  2s. c om*/
#include <stdio.h>

int main(void) {
  int x = SQUARE(1+1); /* 1+1*1+1 = 3 */
  printf("%d",x);
}

Result

The following snippet shows how to break a macro function across several lines.

There must not be any whitespace after the backslash.

#define MAX(a,b)  \
            a>b ? \
            a:b

Related Tutorials