C/Macro Preprocessor/Macro Function

Материал из C\C++ эксперт
Версия от 10:23, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Define Macro as simple function

#include <stdio.h>
#define SUM(i, j) ((i)+(j))
int main(void)
{
  int sum;
  sum = SUM(10, 20);
  printf("%d", sum);
  return 0;
}


Define small function in macro

#define CUBE(x)  x*x*x 
#include <stdio.h>
main () {
    
  int k = 5;
  int j = 0;
  j = CUBE(k); //  j = k*k*k
  printf ("Cube value of j is %d\n", j);
}


Defining a macro to compare two values

/*
The macro function can work with numerical values
of any type. The values can be variables, constants or expressions.
*/
#include <stdio.h>
#define COMPARE(x,y)   ((x)<(y)?-1:((x)==(y)?0:1))
int main()
{
  double a = 1.5;
  int n = 2;
  float z = 1.1f;
  printf("\n compare %lf (double) with %f (float): %d", a , z, COMPARE(a,z));
  printf("\n compare %lf (double) with %d (int): %d", a , n, COMPARE(a,n));
  printf("\n compare %d (int) with %f (float): %d", n , z, COMPARE(n,z));
  printf("\n compare \" n * a\" = %lf \n"
    " with \"n+1\" = to %d (double): %d",
     n*a , n+1, COMPARE(n*a,n+1));
  printf("\n");
}


Defining a macro to output the value of an expression

#include <stdio.h>
#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");
}


Generate a square table

#include <stdio.h>
#define SQR(x) ((x) * (x))
int main()
{
    int counter = 0;
    while (counter < 5)
        printf("x %d square %d\n", counter, SQR(++counter));
    return (0);
}


Make string

#include <stdio.h>
#define mkstr(s)  # s
int main(void)
{
  printf(mkstr(I like C));
  return 0;
}


Use Macro to check the int range

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define RANGE(i, min, max) (i < min) || (i > max) ? 1 : 0
int main(void)
{
  int r;
  /* random numbers between 1 and 100 */
  do {
  
    do {
  
      r = rand();
  
    } while(RANGE(r, 1, 100));
  
    printf("%d ", r);
  
  } while(!kbhit());
  return 0;
}


Use macro to find the minor variable

#include <stdio.h>
#define min(a, b) ((a<b) ? a : b )
int main() { 
   int a,b,c;
   a = 1;
   b = 2;
   c = min ( a, b); 
   printf ( "a: %d, b: %d, c: %d\n", a, b, c );
}


Use Macro to get the bigger int value

#include <stdio.h>
#define MAX(i, j) i>j ? i : j
int main(void)
{
  printf("%d\n", MAX(3, 2));
  printf("%d\n", MAX(1, -1));
  /* this statement does not work correctly */
  printf("%d\n", MAX(100 && -1, 0));
  return 0;
}


Use marco for small function

#include <stdio.h>
#define ABS(a)  (a) < 0 ? -(a) : (a)
int main(void)
{
  printf("abs of -1 and 1: %d %d", ABS(-1), ABS(1));
  return 0;
}