suppose I have a function which accept const reference argument pass,
int func(const int &i)
{
/* */
}
int main()
{
int j = 1;
func(j); // pass non const argument to const reference
j=2; // reassign j
}
this code works fine.according to C++ primer, what this argument passing to this function is like follows,
int j=1;
const int &i = j;
in which i is a synonym(alias) of j,
my question is: if i is a synonym of j, and i is defined as const, is the code:
const int &i = j
redelcare a non const variable to const variable? why this expression is legal in c++?
The reference is const, not the object. It doesn't change the fact that the object is mutable, but you have one name for the object (j
) through which you can modify it, and another name (i
) through which you can't.
In the case of the const reference parameter, this means that main
can modify the object (since it uses its name for it, j
), whereas func
can't modify the object so long as it only uses its name for it, i
. func
could in principle modify the object by creating yet another reference or pointer to it with a const_cast
, but don't.
const int &i = j;
This declares a reference to a constant integer. Using this reference, you won't be able to change the value of the integer that it references.
You can still change the value by using the original variable name j, just not using the constant reference i.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With