C++ Note 020: Comparison of const and #define

 


 Original notes, please indicate the source for reprinting!

Click [Follow], attention is also a virtue~


 

First , const is the same as #define

const constants in C ++ are similar to macro definitions

const  int  c = 5  ≈  #define  c  5

const is a means to replace #define.

Procedure one:

intmain()

{

const int a=10;

printf("a=%d\n",a);

return 0;

}

Procedure two:

#define a 10

intmain()

{

//const int a=10;

printf("a=%d\n",a);

return 0;

}

 

The results of these two programs are the same, both define a constant a, note that there is no semicolon at the end of #define. The following two programs also illustrate this:

#define a 10

#define b 10

intmain()

{

int arr[a+b];

 

system("pause");

return 0;

}

Compilation succeeded!

#define a 10

#define b 10

intmain()

{

int arr[a+b];

 

return 0;

}

Compilation succeeded!

 

Second , the difference

Look at the program:

 

Now a is a macro definition, we know the macro definition, the preprocessing compiler will replace wherever the variable a is, that is, replace a with 10. Therefore, the a defined in the function fun1 can be used in the function fun2, which means that the macro definition has no scope check . Run can pass.

Then if you want to limit the scope of a to the function fun1, you can use the "unload macro" or "cancel macro" #undef to achieve the purpose.

#undef a - here to cancel the macro definition of a;

#undef - cancel all macro definitions here.

 

Looking at the const scope check, we define the variable b in fun1, and its scope is limited to the fun1 function, which is not available in the fun2 function, you can cancel //printf("b=%d\n" ,b); comment, found a compile-time error!

 

Conclusion :

const constants in C ++ are not the same as macro definitions

const constants are handled by the compiler, providing type checking and scope checking;

Macro definitions are processed by the preprocessor, with pure text replacement.

 


 

 Original notes, please indicate the source for reprinting!

 

More exciting, please pay attention to the WeChat public account: programming according to law


 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325691383&siteId=291194637