C_define_const

C language

1.define

#include <stdio.h>
#define PI 3.14
void main(){
	int r = 2;
	double area = r * r * PI;
	printf("%f",area);
	getchar();
}

define a variable definition, can not be modified
Here Insert Picture Description

2.const

#include <stdio.h>
const double PI = 3.14;
void main(){
	int r = 2;
	double area = r * r * PI;
	printf("%f",area);
	getchar();
}

Here Insert Picture Description

Const and the difference 3.define

Here Insert Picture Description
const variable is defined not constant, but is not allowed to change the value of this variable is often variable! With type. Compile and run time type checking of function presence.

is a constant defined not define the type of tape, for simply replace characters. In the pre-compile time work, type checking does not exist.

1, the difference
(1) handling different compilers

#define macros are expanded in the preprocessing stage.
const constants are compiled using the operational phase.
(2) different types and security checks

#define macro is not the type, do not do any type checking, just start.
const constants have specific types, will perform at compile time type checking.
(3) different storage

#define macro expansion is just, how many places, how many times had begun, does not allocate memory. (Macro definition does not allocate memory, variable definition allocates memory.)
Const constants will be allocated in memory (can be a heap may also be a stack).
(4) const can save space and avoid unnecessary memory allocation. E.g:

Constant macro #define NUM 3.14159 //
const doulbe Num = 3.14159; // not the case into the ROM Pi ...
Double the Num = I; Pi // allocate memory in this case will no longer be assigned!
double I = NUM; // compile macro replacement, memory allocation
double j = Num; // no memory allocation
double J = NUM; // macro substitution then, again allocate memory!
const constants defined from the assembly point of view, gives only a corresponding memory address, is not as immediate as #define given, therefore, define a constant const only one copy of the program is running (as is the read-only global variables, static area exists), and a number of constants defined #define copies in memory.

(5) improve efficiency. Normal compilers are not generally constant const allocated storage space, but they are stored in the symbol table, which makes it a constant during compilation, storage and no memory read operation, such that its efficiency is also high.

(6) macro replacement only for replacement, not calculation, not an expression solving;

Acer replaced the pre-compile time, runtime, it does not allocate memory.

He published 198 original articles · won praise 17 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43141726/article/details/104830213