Detailed C language const keyword

const keyword in C language

const was not much used in the actual programming, const constant is the acronym, meaning "constant"! It is a read-only variables defined keywords, or const keyword is often variable definition.

Said const definition is variable, but the equivalent constant; it is defined by a constant, but the property there are variables, so called constant variable . Const constant variables defined by the method is very simple, it can be preceded const in the normal definition of variables, such as:

const int a = 10;

const int variable type and can be interchanged, both are equivalent, i.e., equivalent to the statement:

int const a = 10;

So after modification with const and former unmodified What difference does it make? They are not all equal to 10 do?

The value of the variable is defined with the const ** not allowed to change, which does not allow it to be reassigned, even if you can not assign the same value. ** defined so that it is read-only variables. This means that it must give initial value at the time of definition.

If not initialized when defined, we know that for local variables not initialized, the program will automatically execute when the store into a small negative number. So give it back given initial word is "change its value", and that is a syntax error occurs.

Modified by const variables, whether it is a global variable or a local variable, the life cycle is running the whole process . Life cycle global variables for the entire process of running this for granted. The use of modified const local variables have a static characteristic, the whole process of its life cycle is running. We know that global variables are static, static is the whole life cycle of the program is running. But with modified const local variables only have static characteristics, and it did not become a static variable.

We know that in the stack, static variables are stored in static storage area, and after const local variables to store modified over the variables are stored in memory in the "read-only data segment" in. The read-only data storage segment amounts unmodifiable read-only variables and constants.

Not be a variable length of the array : const although read-only variable is defined, the definition is equivalent to a constant. Read-only variables but also variables, const variable defined as the length of the array still can not. C ++ extends const meaning of the variables used in C ++ can be defined as const length of the array.

const and pointers

const pointer variable and may also be used together, thereby limiting the pointer variable itself, it may limit the data pointer. Const and pointers will use with several different order, as follows:

int a = 1;
int b = 2;
// 情况一
const int *p1 =  &a;
int const *p2 = &a;
// 指针所指向的数据是只读的,也就是 p1、p2 本身的值可以修改(指向不同的数据),但它们指向的数据不能被修改。
// 即: 
// *p1 = 3; 报错,不能修改指向的数据
// p1 = &b; 有效,可以修改变量的指向

// 情况二
int * const p3 = &a; 
// 指针是只读的,也就是 p3 本身的值不能被修改;
// 即:
// p3 = &b; 报错,不能修改指向的地址
// *p3 = 3; 有效,可以修改指向地址的值

// 情况三
// 指针本身和它指向的数据都是只读的
const int * const p4;
int const * const p5;

const variable names from the past is used to modify pointer variable, the variable name away from that is used to modify the data pointer, if near and far have, then modify pointer variables and data at the same time it points to.

const and Function Parameters

const commonly used in the function parameter, if the parameter is a pointer, in order to prevent modification of data within the pointer function can be used to limit const. For example, the function c language standard library

size_t strlen ( const char * str );
int strcmp ( const char * str1, const char * str2 );
char * strcat ( char * destination, const char * source );
char * strcpy ( char * destination, const char * source );

Limit the use of const function parameters, not only can prevent data from being modified, can also give tips when invoked.

non-const and const casts

const char *And char *are of different types, you can not be const char *the type of data assigned to char *a variable of type. But the reverse is possible, the compiler allows the char *assignment of data types to the const char *types of variables.

char *The data points to have read and write permissions, and const char *data pointed to only read access privileges to reduce the data will not cause any problems, but there is a risk of privilege escalation data may occur.

The operation does not work so:

#include <stdio.h>

int main(){
    const char *str1 = "a";
    char *str2 = str1; // 报错,不能给const变量增加权限
    return 0;
}

const 和 define

Many people will confuse it and define the difference at the time of learning const. From the function that they really like, but they have significantly different:

  1. define pre-compiled instructions, const common variable is defined . define macros are defined in the pre-deployment phase, and read-only variable const definition is used in compiling the operational phase.
  2. ** const variables are defined, and define constants is defined. ** define macros defined in the compiler does not exist, it does not take up memory, because it is not a variable, the system will allocate memory to the variable. Const variable nature but often is still a defined variable, the variables having basic properties, there are types of memory cells occupy.
  3. ** const variable is defined, and the macro definition is a constant, so the object const defined data types, and the object is no macro definition data type. ** so the compiler can type security checks for the former, while the latter is only mechanically Character substitution, no type of security check. This makes it easy to go wrong, that is the "marginal issues" or "parentheses issue."

And the difference between C ++

In c ++, the const do not have to create a memory space, and in (c), a const always need a memory space.

After c ++ defined by a constant const, and writes the symbol table (Symbol Table) , making it a compile-time constant, not allocate storage, nor the memory storing the read operation, such that it efficiency is very high.

int main(){
    const int a  = 2;
    int* p = (int*)(&a);
    *p = 30; // 直接修改const常量对应的内存空间中的值
    cout<<&a<<endl; 
    cout<<p<<endl;  
    cout<<a<<endl;
    cout<<*p<<endl;
}

operation result:

0x7fffc7920804
0x7fffc7920804
2
30

By modifying the value of the memory space pointer corresponding to the constant const, this modification does not affect the value of the constant itself, because the compiler will not be read to memory space. This is c ++ constant folding (Constant Folding) , coming const constants in the symbol table, and not to allocate the memory. Compiler optimization directly replaced.

Unless you need to use const constants of storage space, the compiler will be forced to allocate a space, but still after const constant value from the symbol table reads, so it will not affect the value of the constant const.

In the C language

int main()
{
    const int a  = 2;
    int* p = (int*)(&a);
    *p = 30;
    printf("%x\n",&a);
    printf("%x\n",p);
    printf("%i\n",a);
    printf("%i\n",*p);
    return 0;
}

operation result

18b1c0e4
18b1c0e4
30
30

c Language Reference may be modified by const modified variable value pointer.

c and c ++ const similarities and differences between the summary

  • c const global language will be stored in read-only data segments . When the global const c ++ declaration externor Taking the address of the variable in the read-only data segment compiler allocates memory address, variable storage. Both were protected read-only data segment can not be modified.
  • c language in the stack area, but can not be modified directly by the local variable values ​​read only memory const const variable, but may skip the check compiler modified indirectly by a pointer const value. And c ++ is:
    • For the underlying data type, put it in the symbol table, which allocates memory when its address is taken, allocates memory.
    • For basic data types, if a variable is initialized const variables have been initialized, it will allocate memory.
    • Since for a given data type, such as class objects, you will then allocate memory.
  • c, const default external connection, c ++ const defaults to the internal connections . When the c language two files have const int athe time, the compiler will report an error redefined. In c ++, you will not, because c ++ const in default are internally connected.

Reference material

const keyword and its role (usage), C language const explain
the role of c language and parsing const
c and c ++ const of some differences about

Released five original articles · won praise 0 · Views 59

Guess you like

Origin blog.csdn.net/taokexia/article/details/105337650