Knowledge of C language that you don’t know

table of Contents

 

Define constants:

#define preprocessor

const keyword


Define constants:

In C, there are two simple ways to define constants:

  1. Use  #define  preprocessor.
  2. Use the  const  keyword.

#define preprocessor

The following is the form of using #define preprocessor to define constants:

#define identifier value

For details, please see the following example:

#include <stdio.h>

#define LENGTH 10   
#define WIDTH  5
#define NEWLINE '\n'

int main()
{

   int area;  

   area = LENGTH * WIDTH;
   printf("value of area : %d", area);
   printf("%c", NEWLINE);

   return 0;
}

When the above code is compiled and executed, it will produce the following results:

value of area : 50

const keyword

You can use the  const  prefix to declare constants of a specific type, as follows:

const type variable = value;

For details, please see the following example:

#include <stdio.h>

int main()
{
   const int  LENGTH = 10;
   const int  WIDTH  = 5;
   const char NEWLINE = '\n';
   int area;  

   area = LENGTH * WIDTH;
   printf("value of area : %d", area);
   printf("%c", NEWLINE);

   return 0;
}

When the above code is compiled and executed, it will produce the following results:

value of area : 50

Please note that it is a good programming practice to define constants as capital letters.

Guess you like

Origin blog.csdn.net/weixin_44643510/article/details/112992443