19

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,

curiousguy
  • 8,038
  • 2
  • 40
  • 58
ravi
  • 3,304
  • 6
  • 25
  • 27
  • 3
    It will work if you declare it as: `const float* a;` – Mysticial Jul 17 '12 at 01:01
  • 1
    Well you can make it `const float *a` in `main`, or `const float * const &a` in the function signature. I'm not sure what you want exactly. – chris Jul 17 '12 at 01:01
  • 1
    I want to know reason for this behavior. Why is it not compiling when I pass by reference. I can not just simply change declaration as it would affect other calls where this variable is used. – ravi Jul 17 '12 at 01:04

1 Answers1

28

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;
}
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 4
    I just want to emphasize: "must be added from the greatest indirection level _first_," because when `const` is added at a higher level it's also allowed at lower levels: `int foo(float const * const &a)`. – bames53 Jul 17 '12 at 01:12
  • Could you please point a novice like me to something that talks about *covariant operation* or *greatest indirection level*? Thanks.. – Vijay Chavda Aug 26 '19 at 19:01