Const variable assignment error analysis, const variable assignment report
Const variable assignment Error Analysis const variable assignment Error
The assignment of values from variables to constants is legal in C ++ syntax,
For example, smooth from char to const char;
But the compiler reports an error from char ** to const char:
error: invalid conversion from `char**' to `const char**'
Example:
int main(int argc, char *argv[]){ char a = '1'; const char b = a; char * a2 = "12345"; const char * b2 = a2; char** a3 = NULL; //const char** b3 = a3; //error char** const c3 = a3; //ok char* const * d3 = a3; //ok}
Cause:
Const char ** b3 indicates that the pointer of b3 can be changed and can be directed to another address;
B3 and a3 are unqualified, but b3 points to the object type pointer to const char,
The object type pointed to by a3 is pointer to char. The two are incompatible types,
The value assignment is invalid because the two operands must point to the compatible type.
For more detailed explanations, see reference 1;
Char ** const c3 = a3; correct, it is because const limits the address change of c3 pointer, that is, it points to a3 and can no longer point to other pointers; this limits the potential problems that may occur when the pointer address is changed;
Of course, using a forced type conversion at this time can solve this compilation error:
const char** b3 = const_cast<const char**>(a3); // ok
However, it is difficult to troubleshoot the code after conversion;
Potential problems of forced type conversion
See the following example:
Class Foo {public: Foo () {I = 1;} void modify () {// make some modification to the this object I = 2;} void print () const {cout <"Foo_ I:" <I <endl;} private: int I ;}; // demonstrate potential dangers // error: invalid conversion from 'foo ** 'to 'const Foo **'///////////////////////// /// // int main (int argc, char * argv []) {const Foo x; Foo * p; // const Foo ** q = & p; // q now points to p; this Is (fortunately !) An error const Foo ** q = const_cast <const Foo **> (& p); * q = & x; // p now points to x p-> modify (); // Ouch: modifies a const Foo !! X. print (); // print: Foo_ I: 2 return 0 ;}
We have defined the Foo of a constant. The constant Foo method always prints 1;
An error is returned when converting Foo ** to const Foo,
Use a strong escape character to make compilation pass,
The final result of x. print () is 2; this potential danger is hard to find in the formal project code;
It is hard to think that a const object can be changed;
References: