Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Clear11 keyword const

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is to explain how to use the keyword "const". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the keyword const.

I. History

In theory, the best way to understand why something is put forward is to look for the historical background at that time and the story around it.

But I am very sorry, I did not find the background put forward by const in C language, but a history that can be referenced is that the data form of constant has been reflected in assembly language as early as possible. Constant in assembly language is a definite value. In the assembly stage, you can determine that the code is directly encoded in the instruction code, not the variable amount saved in the register.

Constant is a requirement, and there is no reason why the C language should not retain this tradition. Naturally, the const keyword appears.

II. Similarities and differences between C and C++

As the name implies, the most basic function of const is to ensure that the data is not modified and is only readable. This is like a file without write permission, which can only be viewed from a distance.

Const is one of the 32 keywords in C language (49 in C++). It mainly plays the role of type modification and can be understood as the attribute of a variable. For example, const int a = 10 int a = 10 from right to left defines and initializes a variable an equal to 10, and then modifies the variable with const to tell the compiler that the variable is immutable. In order to maintain the security of the program, because the const can no longer be changed once modified, then const int a; will generate a random value and can never be modified, which is very insecure, so the C compiler will require you to initialize it as soon as you define it. You can also see the strength of the const keyword from here.

Where on earth should I put the const?

Before discussing the use of const in detail, you must first understand that const is a type qualifier (type quailier) in C, a part of a type, and that the closer the const is, the more it modifies who is a constant type.

From the perspective of the basic data types of the C language, it can basically be abstracted into the following categories

Basic data type (integer, floating point)

For the underlying data type, using const is simply defined as an immutable quantity, and since no other type qualifiers are involved, const is valid wherever it is placed.

Const int i = 10\ (\ Leftrightarrow\) int const i = 10 but usually const comes first.

Pointer type (pointer)

Pointer types are very different from the underlying data types.

Do not use a const-modified pointer, which means that the pointer must point to a variable. An error will be reported when it points to a const-modified variable.

Const int a = 10 witint * ptr = a; / / error

When const is placed before int *, it indicates that the pointer type is of type const int, so according to the definition of the pointer type, the pointer must point to a quantity of type const int, that is, a constant.

Const int b = 100th Const int * a = & b

When const is placed after int *, int * const a, obviously from the regular definition of the pointer type, we can only speculate that this is a pointer to the int type, so what is the role of const? (see code below)

Int c = 10, b = 20 Const int b = 30 * const a = & c; / there is no error here, proving that there is a pointer type before the * sign, which is true / / 1. But when we try to change the direction, a = & b; / there will be an error here! This means that when the const is close to the variable name, it means that the pointer cannot be changed after pointing to a variable. What if int * const an is not initialized in the first place? Int * const a; / / an error will be reported here / / 3. What if I try to get him to point to a const quantity? Int * const a = & b; / / error will be reported here

And so on, you can get an unmodifiable pointer to the const variable.

Const int b = 10 Const int * const a = & b

So we can give a summary.

When const is close to the variable name, it means that the pointer must point to a variable of the same type as the pointer.

Once you point, you cannot change the direction.

Unable to point to constant

Complex data types (enumeration, structure, sharing)

For complex types, due to the nesting of simple types, there will naturally be the nesting relationship of const. Here is an example of a structure.

When const is nested in the body of the structure.

Typedef struct a {const int b; int c;} A tint main () {An aa; aa.b = 10; / / an error will be reported here}

In C, using const modifier inside a structure will not report an error, but this variable can no longer be modified, meaning it is an invalid quantity that cannot be initialized or modified (but thanks to C++ 's object-oriented mechanism, we can still define const and assign a value to it).

Use const when defining structures

Const A bb

An error will also be reported at this time, and it is relatively more serious than above, when all the values within the structure are chaotic and cannot be modified.

Due to the introduction of several new programming modes in C++, the scope of const has been further expanded.

Attributes and member functions in a class

The legacy of the structure (that is, the constant properties of the class)

First of all, let's solve the problem of the structure in the previous C language. The requirement is to define const variables inside the structure, knowing that the variables inside the structure cannot be initialized directly, and the structure in C++ can be understood as a class, but with different permissions, you can also have a constructor.

So can it be initialized in the constructor? (the following code will report an error)

Struct a {a () {b = 100;} const int b;}

It's not what we think, but it's very close, and there's another way to initialize a class's variables, using an initialization list (the class's initialization list has a very high priority).

Struct a {a (): B (100) {;} const int b;}

Or there's more.

Struct a {const int b = 100;}

Use C++ feature to assign values directly, and this code will report an error in C language, which is also one of the differences between C and C++.

In this way, the problem of const quantity of structure is solved perfectly.

Static variable of the class vs const variable

Static is also a modifier that determines the lifetime of a variable. Const feels that the readability of variables has a different meaning in a class than in a main function.

Static const int a; / / this statement will report an error in main because it will not be initialized / / in the class

This is because static does not affect the expression of const, and it is stated in the main function that this variable is of type const, which really needs to be assigned immediately. But in the class can be less anxious, you can understand the static variable in the class as a declaration, directly defined outside or inside the class, will not report an error.

Function const and const modification of class member functions

Const of ordinary function

The first thing that comes to mind in the function const is the return value of the const variable. But it doesn't really make much sense.

The return value of const modification actually doesn't work at all and is an invalid modifier. The same is true when you use const to modify formal parameters, which does not limit whether you pass in const or ordinary variables. The essence is that this process occurs due to value transfer. Whether you return const or use const to modify formal parameters, variables are created and assigned internally.

The example of const modified parameter

Int fun (const int a) {/ / a = 10 will report an error return a} int main () {int c = 10; int d = fun (c); / / will not report an error}

As above, when c is passed in, it takes the value of c, and then the function pushes the stack, creating a const int variable an and initializing it to the value of c immediately, so a const variable is generated inside the function. It has nothing to do with what value is passed in.

Const tail modification of member functions

This is a characteristic of C++. Adding a const to the tail of the member function restricts the modification of the object by this function and improves the readability of the code.

Class A {private: int a * public: static int B; int getA () const {A const B = 100; / / there will be no error a = 100; / / there will be an error of a = 100; / / here an error will be reported: return a;}}; int A Vera B = 100

Using const to modify a member function makes the function const member function. This type cannot modify the data of an object, but you can modify static variables that can be modified.

Quote

References don't have as many variants as pointers, and the const modifications of references are limited to making reference variables unmodifiable to point to.

To add one more point.

When const modifies a class static integer variable, it can be initialized directly inside the class (floating-point numbers still don't work).

At this point, I believe that you have a deeper understanding of "how to use the keyword const 11". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report