Reputation: 112
I'm trying to compile the following piece of code, but I'm getting a C2440 (visual studio) error. I've tried looking at other resources for help, but I can't find a good explanation.
int main()
{
int a = 100;
SomeFunction(&a);
}
void SomeFunction(const int* value)
{
//This line of code gives me the error.
int* variable = value;
cout << "Value is " << *Variable << " end" << endl;
}
I know I can solve this problem by using int* variable = const_cast<int*> (value);
, but I still don't understand why the above code is causing a problem.
Upvotes: 0
Views: 23287
Reputation: 2183
const int *
means that the function guarantees that value at this address will not change, but if you can do:
int * variable = value;
Then you can also do
*variable=30;
In doing so, the guarantee of function that is of const pointer will be harmed.
Upvotes: 1
Reputation: 254461
The error's quite clear - a pointer conversion can't remove a const
qualifier; otherwise, you could violate the constness:
int* variable = value; // Not allowed - but if it were...
*variable = 42; // BOOM! changed a constant.
If you don't want to be able to change the value being pointed at, then keep it const
const int* variable = value;
If you do want to change it, then don't make it const
in the first place:
void SomeFunction(int* value)
I know I can solve this problem by using
const_cast
That's a bad idea - you'll get undefined behaviour if you abuse const_cast
and try to modify a constant object. You should use const
where you can, but not when you want to modify something.
Upvotes: 18
Reputation: 283644
The const int*
means that you have the address of an int
that you are not allowed to change.
An int*
can be used to change the int
it points to. Clearly that violates the above statement that you aren't allowed to change it.
const_cast
does not actually "solve the problem". It lets you request to change something which cannot be changed. Such an attempt can cause your program to fail in uncontrolled ways (formally, undefined behavior). In your particular example, the variable a
in main
is not const
, and so const_cast
will successfully change it. But that creates close coupling and contradicts the promise made by a function whose signature is const int*
.
Upvotes: 12
Reputation: 12658
int* variable = value;
is wrong.
It should be,
int variable = *value
and
cout << "Value is " << variable << " end" << endl;
Upvotes: 2