C/Macro Preprocessor/Macro Constant

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Define constant in Macro

#include <stdio.h>
#include <assert.h>
#define ROW_Constant 10
#define COL_Constant 10
int main() {
  int row, col;
  for ( row = 1; row <= ROW_Constant; row++) {
      assert ( row <= ROW_Constant );
      for ( col = 1; col <= COL_Constant; col++ ) {
          assert ( col <= COL_Constant );
          printf ( "%4d", row * col );
      }
      printf ( "\n" );
  }
}


Define constant in Macro for loop control

#include <stdio.h>
#define count 31
int main() {
    int heat[count];
    int i;
    float celsius;
    
    for(i = 0; i < count; i++) {
        celsius = ( 5.0 / 9.0 ) * ( heat[ i ] - 32);
        printf("%d \t \t%6.2f \n", heat[ i ], celsius);
    }
}


Define header file name in macro

  
#define STDIO <stdio.h>
#include STDIO
int main(void)
{
  printf("This is a test.");
  return 0;
}


Define Macro and use it as the loop condition

  
#include <stdio.h>
#define MAX 100
int main(void)
{
  int i;
  for( i = 0; i < MAX; i++) 
      printf("%d ", i);
  return 0;
}


Define macro: constant

/* Define macro */
#include <stdio.h>
#define  PI 3.14159f                  /* Definition of the symbol PI */
void main()
{
   float radius = 0.0f;
   float diameter = 2.0f;
   float circumference = 0.0f;
   float area = 0.0f;
   radius = diameter/2.0f;
   circumference = 2.0f*PI*radius;
   area = PI*radius*radius;
   printf("\nThe circumference is %.2f", circumference);
   printf("\nThe area is %.2f", area);
}


Define macro for string and output

  
#include <stdio.h>
#define FUN "Macro Substitutions"
int main(void)
{
  printf(FUN);
  return 0;
}


Define macro inside the main function

  
#include <stdio.h>
void f(void);
int main(void)
{
  #define LIGHTSPEED 186000
  f();
  return 0;
}
void f(void)
{
  printf("%ld", LIGHTSPEED);
}


Define Macro: TRUE and FAlSE

#include <stdio.h>                     /* For input and output             */
#define TRUE  1                        /* Defines the symbol TRUE      */
#define FALSE 0                        /* Defines the symbol False     */
void main()
{
     int correct = TRUE;  /* By default indicates correct sequence entered */
     printf("%s\n", correct? "Correct!" : "Wrong!");
}


Define marco based calculation

  
#include <stdio.h>
#define SMALL 1
#define MEDIUM SMALL+1
#define LARGE MEDIUM+1
int main(void)
{
  printf("%d %d %d", SMALL, MEDIUM, LARGE);
  return 0;
}


Use Macro

#define BIG_NUMBER 10 * 10
main()
{
    int   index = 0;
    while (index < BIG_NUMBER) {
        index = index * 8;
    }
    return (0);
}