CONST in functions, methods, etc.

xiaoxiao2021-03-06  56

Const itself is defined for constants, such as

Const int buffsize = 512;

So can this constant are referenced by an integer pointer, such as int * ptr = & buffsize;

Due to the limitations of the compiler (which cannot be tracked in any point pointing, this requires data stream analysis), this compilation cannot be passed. So, this is to define a constant pointer: const int * ptr;

Constants can be cited with constant pointers, but cannot be modified. At the same time, constant pointers can also point to variables, but cannot modify this variable by pointer: PTR = & buffsize; // ok

INT size = 16; PTR = & size; // ok * ptr = 17; // Will Cause An Error

It can be seen that the constant pointer is for the amount of Const.

Now turn over and see this function definition: int strcmp (const char * str1, const char * str2); what does it mean? In the actual program, pointing to the pointer of Const as a formal parameter, which is guaranteed as an agreement that the actual object passed to the function will not be modified in the program.

Finally, if you want to define a complete constant pointer? As follows: Const Double Pi = 3.14159265; Const Double * Const PTR = & PI;

A Related Reference: / ************** Begin of constptr.cpp ****************** /

#include using namespace std;

INT Main (int Argc, char * argv []) {const Double pi = 3.14158265; const double * ptr;

PTR = & PI;

COUT << "The value of pointer /" ptr / "is" << * Ptr << ENDL;

Double Radius = 3.0; Double Area = PI * RADIUS * RADIUS;

PTR = & area;

COUT << "The value of pointer /" ptr / "is" << * Ptr << ENDL;

/ ******* TEST Const Ptr *********** / Const Double * const p2 = & pi;

COUT << "The value of p2 is" << * p2 << Endl;

/ * P2 = & area; // Will Cause An Error Here Cout << "The value of p2 is" << * p2 << Endl; * /

Return 0;}

/ ************** * endof constptr.cpp ***************** // ******************* ****** Build: g -o constptr constptr.cpp ******* /

转载请注明原文地址:https://www.9cbs.com/read-118113.html

New Post(0)