I am confused that why following code is not able to compile
int foo(const float* &a) {
return 0;
}
int main() {
float* a;
foo(a);
return 0;
}
Compiler give error as:
error: invalid initialization of reference of type 'const float*&' from expression of type 'float*'
but when I try to pass without by reference in foo, it is compiling fine.
I think it should show same behavior whether I pass by reference or not.
Thanks,
You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to. This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.
The rules for initializing references make passing by reference-to-const an efficient and attractive alternative to passing by value. As in C, function calls in C++ normally pass arguments by value. For example, given: int abs(int i);
But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.
Because it isn't type-safe. Consider:
const float f = 2.0;
int foo(const float* &a) {
a = &f;
return 0;
}
int main() {
float* a;
foo(a);
*a = 7.0;
return 0;
}
Any non-const
reference or pointer must necessarily be invariant in the pointed-to type, because a non-const
pointer or reference supports reading (a covariant operation) and also writing (a contravariant operation).
const
must be added from the greatest indirection level first. This would work:
int foo(float* const &a) {
return 0;
}
int main() {
float* a;
foo(a);
return 0;
}
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