I usually use C type casting in C/C++ code. My question is, does adding the "const" keyword in the casting type mean anything to the result?
For example, I can think up several scenarios:
const my_struct *func1()
{
my_struct *my_ptr = new my_struct;
// modify member variables
return (const my_struct *)my_ptr;
// return my_instance;
}
In this one, the function constructs a new instance of a struct, and casting it to to a constant pointer, therefore caller will not be able to further modify its internal state except deleting it. Is the "const" casting required, recommended, or simply unnecessary, since either return statement works.
In this one, my_base
is the base class of my_derive
.
const my_base *func2(const my_derive *my_ptr)
{
return (const my_base *)my_ptr;
// return (my_base *)my_ptr;
}
Since my_ptr
is already a const pointer, would casting it with (my_base *)
involve a const_cast for removing const and another implicit const_cast when returning?
Is there any reason to add "const" to an integer function argument, since changing it never affect state outside the function?
void func3(const int i)
{
// i = 0; is not allowed, but why, as it is harmless?
}
How about adding "const" when casting an integer? I think this should resemble func2()
.
void func4(short i)
{
const unsigned int j = (const unsigned int) i;
// const unsigned int j = (unsigned int) i;
}
Correct me if I'm wrong. Considering type casting might be an FAQ, I'm not sure if this one duplicates with anything else. Thanks!