C macro

Definition

A macro is #define directive with multiple parameterized substitutions.

Syntax

The general form of the kind of substitution directive just discussed is the following:

#define macro_name( list_of_identifiers ) substitution_string

Example 1

Replacement of the identifier by using a statement or expression.


#define CUBE(x)  x*x*x/*from   w  w  w  . ja v  a2  s .co  m*/
#include <stdio.h>

main (){
    int k = 5;
    int j = 0;
    j = CUBE(k);

    printf ("value of j is %d\n", j);
}

The code above generates the following result.

Example 2

Macro just indicates replacement, not the function call.


#include <stdio.h>
//from   w w  w.  j ava  2s.  c  o  m
#define add(x1, y1)  x1 + y1
#define mult(x1,y1)  x1 * y1

main ()
{
    int a,b,c,d,e;
    a = 2;
    b = 3;
    c = 4;
    d = 5;
    e = mult(add(a, b), add(c, d));

    // mult(a+b, c+d)
    // a+b * c+d

    printf ("The value of e is %d\n", e);
}

The code above generates the following result.

Example 3

Defining a macro to output the value of an expression


#include <stdio.h>
/*from  w  w  w  .  j  a  v  a2 s.co  m*/
#define print_value(expr) printf("\n" #expr " = %lf", (double)expr);

void main() {
  int n = 10;
  double f = 6.5;

  print_value( n );
  print_value( f );
  printf("\n");

  print_value(f * f + 4.0);
  print_value( n / 2 + 3);
  print_value( 3 * 4 + 12 / 2 - 8);
  printf("\n");
}




















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing