- Which compiler is likely to create a const literal, but it is not a variable.
A non-constant reference cannot point to a literal.
$ g ++ test.cpp test.cpp: In the int main()': test.cpp:10: error: invalid initialization of non-const reference of type 'double&' from a temporary of type 'double' test.cpp:5: error: in passing argument 1 of function int main()': test.cpp:10: error: invalid initialization of non-const reference of type 'double&' from a temporary of type 'double' test.cpp:5: error: in passing argument 1 of double foo (double &) '
test.cpp:
#include <iostream> using namespace std; double foo(double & x) { x = 1; } int main () { foo(5.0); cout << "hello, world" << endl; return 0; }
On the other hand, you can pass a literal to refer to a constant as follows. test2.cpp:
#include <iostream> using namespace std; double foo(const double & x) { cout << x << endl; } int main () { foo(5.0); cout << "hello, world" << endl; return 0; }
Eugene yokota
source share