Talking to Const Keywords

xiaoxiao2021-03-06  212

Today, I was asked, and the const keyword was in combination with the pointer, and speechless. So the following experiments:

Char mychar = 'q';

Char * mypoint = & mychar;

CONST Char * myconst1 = & mychar; char const * myconst4 = & mychar; char * const myconst3 = & mychar;

Const char const * myconst2 = & mychar; const char * const myconst3 = & mychar; char const * const myconst6 = & mychar;

Const char const * const myconst5 = & mychar;

Compile with Intel C Compiler 8.0, draw the following results:

Char mychar = '5'; char * mypoint = & mychar; // Common Pointer /// define for const object // limited extern variable int main () {// Test for const 1 const char * myconst1 = & mychar; // a Pointer Which Point To a const char myconst1 ; // pass myconst1; // pass (* myconst1) ; // error, can not modify the value (* myconst1); // Error, Can Not Modify The Value

// Test for const 2 char const * myconst2 = & mychar; // a Pointer Which point to a const char myconst2 ; // pass myconst2; // pass (* myconst2) ; // error, can not modify the Value (* MyConst2); // Error, Can not modify the value

// Test for const 3 char * const myconst3 = & mychar; // a const Pointer Which Point to a char myconst3 ; // error, can not modify the Pointer myconst3; // error, can not modify the pointer (* MyConst3 ) ; // Pass (* myconst3); // pass

// Test for const 4 const4 = & mychar; // a Pointer Which point to a const char myconst4 ; // pass myconst4; // pass (* myconst4) ; // error, can not modify The value (* myconst4); // error, can not modify the value // test for const5 const char * const myconst5 = & mychar; // a const Pointer Which Point To a const char myconst5 ; // error MyConst5; // error (* myconst5) ; // error (* myconst5); // error

// Test for const6 char const * const myconst6 = & mychar; // a const point Which pointer to a const char myconst6 ; // error myconst6; // error (* myconst6) ; // error ( * MyConst6); // error

// Test for const same char const * const myconst7 = & mychar; // a const pointer Which pointer to a const char myconst7 ; // error myconst7; // error (* myconst7) ; // error ( * myconst7); // error

Return 0;}

in conclusion:

In fact, conclusion is the easiest, constant reads the actual meaning of this Const definition according to the combination of right to left. For example, const char const * myconst and const char * myconst are actually equivalent.

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

New Post(0)