How to Solve Const variable assignment Error

Error analysis of const variable assignment

Const variable assignment error

The assignment from variable to constant is legally agreed by the syntax of C + +,
such as from char to const char
however, the compiler will report 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
}

Reason:
const char * * B3 indicates that the pointer of B3 can be changed and can point to another address
both B3 and A3 are unqualified, but the object type pointed to by B3 is pointer to const char,
the object type pointed to by A3 is pointer to char. They are incompatible types,
do not comply with the provisions that the two operands must point to compatible types, so the assignment is illegal
for a more detailed explanation, see reference 1

 

While char * * const C3 = A3; Correct, because const restricts the address change of C3 pointer, that is, it points to A3, so it can no longer change the pointer to other pointers; This limits the potential problems of pointer address change

Of course, this compilation error can be solved by using a forced type conversion:

    const char** b3 = const_cast<const char**>(a3); // ok

However, if the converted code has problems again, it is difficult to check

Potential problems with cast

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;
};
  
//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 define a constant foo. The constant foo method always prints 1
an error is reported in the conversion from foo * * to const foo * *.
the compiler passes through a strong conversion character,
the result of the last x.print() is 2; Such potential hazards are difficult to find in the formal project code
it’s hard to think that a const object can be changed.

 

Similar Posts: