"Go" to say C language const usage

Source: Internet
Author: User

Words: C Language Const usage

Const is a relatively new descriptor in C, which we call a constant modifier, meaning that it modifies
The object is a constant (immutable).


Let's take a look at the syntax of how it should be used.


1. Modify the local variables in the function body.
Cases:
void Func () {
const int a=0;
}


First, we ignore the word const, then A is a local automatic variable of type int,
Let's give it an initial value of 0.


And then look at the const.


Const as a type qualifier, and int have the same status.
const int A;
int const A;
is equivalent. So here we must clearly understand, the const modification of the object is who, is a, and int no
Have a relationship. Const requires that he modify the object to be constant, not to be changed, not to be assigned, not as an lvalue (L-value).
It is also wrong to do so.
const int A;
a=0;
This is a very common way to use:
const double pi=3.14;
After the program, if you attempt to assign a value to the PI again or modify the error.


Then look at a slightly more complex example.
const int* p;
or remove the const modifier symbol FIRST.
Note that the following two are equivalent.
int* p;
int *p;
In fact, what we want to say is that *p is of type int. So obviously, p is a pointer to int.
Similarly
const int* p;
is actually equivalent to
const int (*p);
int const (*P);
That is, *p is a constant. In other words, the data that P points to is a constant.
So
p+=8; Legal
*p=3; Illegal, the data that P points to is a constant.


So how do you declare a constant pointer to yourself? The method is to let the const as close as possible to p;
int* const P;
Const to the right only p, obviously, it modifies the p, stating that p cannot be changed. Then remove the const and you can
See p is a pointer to an int form variable.
So
p+=8; Illegal
*p=3; Legal


Looking at a more complex example, it is the synthesis of the two above
const int* const p;
The description p itself is a constant, and the variable p points to is also a constant.
So
p+=8; Illegal
*p=3; Illegal


A const also has a function of modifying a constant static string.
For example:
Const char* Name=david;
If there is no const, we may unintentionally write name[4]= ' x ' such statements, which will
Causes the assignment of the read-only memory area, and the program terminates abnormally immediately. With the const, this error is
Can be checked out as soon as the program is compiled, which is the benefit of the Const. Let the logic error be compiled
Period was found.


Const can also be used to modify arrays
const char S[]=david;
has a similar effect to the above.


2. Modifying parameters when declaring a function
Look at an example in practice.
NAME
Memmove--Copy byte string


LIBRARY
Standard C Library (libc,-LC)


Synopsis
#include


void *
Memmove (void *dst, const void *SRC, size_t len);


This is a function in the standard library for copying strings (memory) in bytes.
Its first argument is where to copy the string to (dest), which is the destination, and this memory area must be
is writable.
Its second parameter is what kind of string to copy out, we only do read the memory area
Take, do not write.
So, we stand in this function's own point of view, SRC this pointer, it points to the memory stored in the
The data stored in the entire function is unchanged during execution. So the content that SRC points to is constant. So it
Need to be modified with Const.
For example, we use it here.
Const char* S=hello;
Char buf[100];
Memmove (buf,s,6); This should actually be better with strcpy or memcpy.


If we write in turn,
Memmove (s,buf,6);
Then the compiler will be sure to make an error. The fact is that we often write the arguments of various functions in reverse order. The fact is that
The translator helped us a great favor at this time. If the compiler silently does not error, (remove at function declaration
const), the program will crash when it runs.


It is also important to note that in a function parameter declaration, a const is used to declare a pointer rather than the variable itself.
For example, above size_t len, when the function is implemented, it can be completely without changing Len's value, then whether
Should Len also be declared as constant? Yes, you can do that. Let's analyze the pros and cons of doing this.
If you add a const, then for the implementation of this function, you can prevent him from implementing this function to fix
You don't need to change the value (len), that's fine.
But for the user of this function,
1. This modifier is meaningless, and we can pass a constant integer or a very literal integer over
Go, anyway the other party gets just a copy of our pass.
2. Exposed the implementation. I don't need to know if you have changed Len's value when you implement this function.


Therefore, const is generally used only to modify pointers.


Look at a more complicated example.
int execv (const char *path, char *const argv[]);
Focus on the back, argv. What it stands for.
If we remove the const, we can see
char * argv[];
ARGV is an array in which each element is a pointer to a char * type.
If you add a const. Who is the const modifier? He modifies an array, argv[], meaning
That the elements of this array are read-only. So what is the type of element of the array? is a char * type of reference
Needle. That is, the pointer is a constant, and the data it points to is not.
So
Argv[1]=null; Illegal
Argv[0][0]= ' a '; Legal




3, global variables.
Our principle is still to use as few global variables as possible.
Our second rule is to use the const as much as possible.
If a global variable is used only in this file, then the usage and the previously mentioned function local variables have no
Difference.
If it is to be shared among multiple files, then there is a problem with the type of storage involved.


There are two ways of doing this.
1. Use extern
For example
/* File1.h */
extern const double PI;
/* FILE1.C */
const double pi=3.14;
Then the other needs to use the variable pi, including the File1.h
#include file1.h
Or, make a copy of that statement yourself.
The result of this is that after the entire program is linked, all the variables that need to use PI are shared in a storage area.


2. Static external storage classes using static
/* Constant.h */
static const pi=3.14;
This header file must be included in the *.c file that needs to use this variable.
There must be no less static in front. Otherwise the link will report that the variable is defined multiple times.
The result of this is that each *.c file containing the constant.h has a copy of the variable itself,
The variable is actually defined more than once, takes up more than one storage space, but adds the static keyword
, the conflicts between file redefinition are resolved.
The downside is that the storage space is wasted, resulting in a larger executable file after the link is finished. But usually, this, little
A few bytes of change, not a problem.
The advantage is that you don't have to worry about which file the variable is initialized in.




Finally, talk about the role of Const.
The benefit of const is the introduction of the concept of constants, which let us not modify the memory that should not be modified. Direct.
The function is to let more logic errors be found during the compilation period. So we want to use the const as much as possible.
But a lot of people are not used to it, what is more, the whole program is written/debugged after the completion of
Const If it is a const for the declaration of a function, it is still good. If you are giving a const to a global/local variable, that
..... Well, it's too late to make the code look prettier. With regard to the use of const, there had been a
A joke says, the const is like the condom, beforehand must remember. If you do not remember to use and forget to use,
Oh...... Oh......

"Go" to say C language const usage

Related Article

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.