C language Keyword const usage __c language

Source: Internet
Author: User
Tags array definition constant int size modifier variable scope
the const in C language

A const is a reserved keyword in the C language that defines constants, and if a variable is modified by a const, its value cannot be changed. Code written with symbolic constants is easier to maintain; some pointers are often moved by side-reading rather than by writing; many programming specifications force the requirement of read-only writing for function parameters, in which case the const implementation is required.

Then some people will ask, C language is not already exist #define, why also use the Const. The following advantages are compared to the #define,const modifier:
1. const enables the compiler to perform type checking, while the precompiled instruction #define simply replaces the value.
2. Const can protect the modified variables and so on, to prevent the variable from accidentally modified, thereby enhancing the robustness of the program.
3. Compilers typically do not allocate storage space for ordinary const constants, but instead store them in a symbol table, which makes it a constant during compilation, without memory manipulation, making it efficient. Const Usage

The most common use of const is as an array of bounds and switch sub-status labels, categorized as follows:
Constant variable: const + type descriptor + variable name
Constant reference: Const + Type descriptor + & reference name
Constant object: Class name + Const object Name
Regular member functions: Class Name:: Fun (formal parameter) + const
Constant groups: Type descriptor + Const array name [size]
Constant pointer: const + TYPE descriptor * Pointer name or type specifier + const * pointer name
The first clue is: in constant variables (const + type specifier + variable name), constant reference (const + type specifier + & reference name), constant object (class name + Const object name), const group (type specifier + const array name [size]), constants "and" type The location of the specifiers "or class name" (in fact the class name is a custom type descriptor) can be interchanged. Such as:

const int a=5; 
int const a=5; Equivalent

In fact this can be very well understood, the const can only modify int (type name or class name), so the two are equivalent. modifying local variables

const int n=5;
int const n=5;

The two writing is the same, are to indicate that the value of the variable n can not be changed, it should be noted that the use of the const modifier variable, be sure to initialize the variable (except to modify the function of the parameters), otherwise it can no longer be assigned.
Next look at the const for modifying constant static strings, for example:

Const char* str = "FDSAFDSA";

Without a const modifier, we might write a statement str[4]= ' X ' in the back, which would result in an assignment to the read-only memory area, and then the program would terminate abnormally immediately. With the const, this error can be checked out as soon as the program is compiled, which is the benefit of Const. Let logical errors be found at compile time. constant pointers and pointer constants constant Pointer

A constant pointer represents a pointer to a constant that is a constant (at least the constant pointer does) and can be defined as follows:

const int * n;
int const * N;

The following two points need to be noted:
1. The value that the constant pointer points to cannot be changed, but that does not mean that the pointer itself cannot be changed, and constant pointers can point to other addresses.

int a=5;
int b=6;
Const int* n = &a;
int const *N1 = &a; 
n=&b;

In this example, N and N1 are equivalent, all pointing to a constant pointer to a, when one would say that a constant pointer should be a constant, but a is not a constant, why is a constant pointer still pointing to a?
The compiler allows the address of a non-const object to be assigned to a pointer to a const object and does not allow the address of a const object to be assigned to a normal, non-const object pointer.
In fact, this is also very well understood, for a variable, I can add restraints to you, pointing to you with a pointer to a const object, which means I now think you are a constant and cannot modify you with this constant pointer, but for the second case, you are a bound constant, Pointing at you with a normal pointer means I think you're a variable, so maybe I'll modify your value in the following code, modify a const constant, and what happens, you should understand.
And then back to the code above, we gave the address of a to n, and then we changed the value of N on the next line, assigning B's address to N, which is not a problem, because n is just a pointer to a constant, so it's called a constant pointer, and it's still a normal pointer, and it's very special about what it's pointing to. , rather than it itself. So its own values can be modified to point to different content.
2. When the constant pointer points to a variable, you cannot change the value of the variable through the constant pointer, but you can still change the value of the variable by using another reference.

int a=5;
Const int* n=&a;
a=6; Correct
*n = 7;//error, for constant pointers, you cannot change what you point to (even if the content it points to is not a constant).
int *ni = (int *) n;
*n = 100; That's right

In the eye of N, where n is pointing to a constant, it is not allowed to be modified by n itself, but a is essentially a variable, so we can modify it directly through the variable name or the new normal pointer. In fact, when the program is loaded into memory, there is a special piece of memory area to hold the constant. However, the above a itself is not a constant and is stored in stacks or heaps. We can still modify its value. and N cannot modify the point value should be said to be a compiler limit. Pointer Constants

A pointer constant is a constant that points to a fixed address and cannot point to another address. The wording is as follows:

int *const N;

Unlike the constant pointer above, the pointer constant refers to the pointer itself as being special, and the content it refers to is not special, so the content that the pointer constant points to can be modified and can be modified by another pointer to that address. As shown below:

int a=5;
int *p=&a;
int* Const n=&a;
*p=8;

In a function, a pointer constant indicates that the pointer is not allowed to point to other content:

void func_02 (int* const p)
{
    int *pi = new int (m);
    /* error. P is a pointer constant. You cannot assign a value to it. * *
    p = pi;
}

int main ()
{
    int* p = new int (a);
    Func_02 (p);
    Delete p;
    return 0;
}

Then look at the following code:

const int *M1 = new int (a);
int* const m2 = new int (20);

In the top two expressions, the easiest thing to confuse is whether the const is a cosmetic pointer or a memory area that the pointer points to. In fact, just know: theconst only works on its left side, the only exception is that the const itself is the leftmost modifier, then it will work on the right thing. Judging by this rule, M1 should be a constant pointer (that is, you cannot modify the content it points to by M1.) And M2 should be a pointer constant (that is, you cannot have M2 point to another memory address). Or we can think of the asterisk as a pointer, the const as a constant, then M1 is a constant pointer, M2 is a pointer constant. constant pointers to constants

Is the combination of the two, the position of the pointer can not be changed and can not change the value of the variable through the pointer, but when it points to a variable, you can still change the value of the variable through other normal pointers.
const int* const p; parameters of the modifier function

Depending on the constant pointer and the pointer constant, the parameters of the const modifier function are divided into three different cases
1. Prevent changes to the contents of the pointer

void Stringcopy (char *strdestination, const char *strsource);

Where strsource is an input parameter, strdestination is an output parameter. After adding a const modifier to the strsource, the compiler will point out an error if the statement in the body of the function attempts to change the contents of the strsource. This form is typically used to simulate a value call in an array-form parameter. Which is the equivalent of the function caller claiming: "I'll give you a pointer to it, but you can't modify it." "If the function writer follows this convention, it is equivalent to simulating value delivery." This is also the most useful thing about const: to qualify a function's formal parameters so that the function will not modify the data that the argument pointer refers to. notice here that the function should not be modified, not modified, which means that the const cannot prevent the parameter from being modified (see the reason).
2. Prevent modifying the address that the pointer points to

void swap (int* const P1, int* const p2);

Both the pointer p1 and the pointer p2 are pointer constants, and the addresses you point to cannot be modified. The return value of the modifier function

Most of the time, our function returns an address or reference. Call this to the returned address or reference to modify the object being pointed to or represented. This time, if we don't want this function call to modify this returned content, we should return a constant.
If you modify the function return value with the "pointer Pass" method, the contents of the function return value (that is, the pointer) cannot be modified, and the return value can only be assigned to the same type of pointer with the const modifier.
such as functions

const char * GetString (void);

The following statement will present a compilation error:

Char *str = GetString ();

The correct usage is

const char *STR = GetString ();
To decorate a global variable

Global variable scope is the entire file, we should try to avoid the use of global variables, that once a function changes the value of the global variable, it will also affect other reference to the variable function, resulting in addition to the bug is difficult to find, if you must use global variables, We should try to decorate with the const modifier as much as possible, so that it is not necessary to modify the method in the same way as the local variable.the difference between const in C and C + +In C + +, the const is normally regarded as a compile-time constant, and the compiler does not allocate space for const, but saves the period value in the name table at compile time and in the appropriate time in the code. So the following code:
using namespace Std;
int main ()
{
const int a = 1;
const int b = 2;
int array[A + b] = {0};
for (int i = 0; i < sizeof array/sizeof *array; i++)
{
cout << array << Endl;
}
}
Can be compiled and run normally. But after a little modification, put in the C compiler, there will be an error:
int main ()
{
int i;
const int a = 1;
const int b = 2;
int array[A + b] = {0};
for (i = 0; i < sizeof array/sizeof *array; i++)
{
printf ("%d", array);
}
}
Error message:
C:\TEST1\TE.C (8): Error C2057: Constant expression should be entered
C:\TEST1\TE.C (8): Error C2466: Cannot allocate an array with a constant size of 0
The reason for this is that in C, the const is a normal variable that cannot be changed, and since it is a variable, it occupies storage space, so the compiler does not know the value at compile time. Also, the subscript for an array definition must be a constant. In the C language: const int size; This statement is correct because it is treated as a declaration by the C compiler, indicating that storage space is allocated elsewhere. It is not correct to write this in C + +. In C + +, the const default is an internal connection, and if you want to achieve the above effect in C + +, you must use the extern keyword. In C + +, Const uses an internal connection by default. and C uses an external connection.
(1) INNER join: The compiler creates only the storage space for the file being compiled, and other files can use the same notation or global variable. The internal connections in C/A + + are specified using the static keyword.
(2) Outer joins: All the compiled files create a separate storage space. Once the space is created, the connector must resolve the reference to the storage space. Global variables and functions use external connections. By declaring the extern keyword, you can access the corresponding variables and functions from other files.Reference Links:

The const keyword detailed in C + +
The usage of the Const keyword in c language
In the words of the C language Const usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.