Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the const qualifier of C++

Shulou Source: shulou.com Published: 2022-06-02 05:53:29 10月05日 Update

This article introduces the knowledge of "how to use C++ 's const qualifier". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Const qualifier: defines a variable as a constant

1. Use const to define the type of variable, and the value of the variable cannot be changed

Const int bufSize=512;// input buffer size bufSize=512;// error because an equal sign attempted to write a value to the const object

The 2.const object must be initialized (it cannot appear to the left of the equal sign at other times)

Const int i=get_size (); / / initialize const int at correct runtime / initialize const int at compile time / const int bb=0;void is not initialized at correct compilation / const int bb=0;void is not initialized at compile time / bb is compiled to a constant at compile time and is handled as a constant at compile time

3. By default, const objects are only valid within files. To share const objects within multiple files, you must add the extern keyword before the variable definition.

Extern const int bufSize=fcn ()

References to 4.const: references to constants

The correct reference of const int ci=1024;const int&r1=ci;// and the objects it binds are constants r _ 1 _ r _ 42 _ / / error cannot point to a constant with a non-constant reference

5. Pointer and const

A pointer to a constant

Const doublenpi=3.14;double * ptr= π / / error const double * cptr= π * cptr=3;// error double dval=3.14;cptr=&dval;// is correct but the value of dval cannot be modified through cptr

Const pointer: a pointer is an object or can be limited to a constant (must be initialized)

Put * before const, indicating that the pointer is a constant, and what remains constant is the value of the pointer itself rather than the value it points to

Int errNumb=0;int * const curErr=&errNumb;const double pi=3.14159;const double * const pip= π / / constant pointer to a constant * pip=2.71;// error attempted to modify the constant pipif (* cureRR) {errorHandler (); * curErr=0;// correctly tried to modify the variable erNumb} "how to use the const curErr=&errNumb;const double pi=3.14159;const double qualifier of C++". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Constant error pointer object variable point compile clocked content situation file time more knowledge equal sign type practical effective learned next Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Tech Info Redmi Microsoft Docker