Search code examples
c++referenceturbo-c++borland-c++

Why int& a=10; is valid in ancient C++ compilers?


I was just wondering why ancient compilers like Turbo c++ 3.0(Blue screen IDE) & Borland Turbo C++ 4.5 etc doesn't report any error in following program.

#include <iostream.h>
int main()
{
  int& a=10;
  cout<<a;
  return 0;
}

The above program won't be accepted by modern C++ compilers, But why then ancient compilers allows this? They simply shows single warning in above program.


Solution

  • It used to be valid C++ to bind a reference to a temporary, so you could pass e.g. double to a function expecting int&, as explained in The Design & Evolution of C++ §3.7:

    I made one serious mistake, though, by allowing a non-const reference to be initialized by a non-lvalue. [...]
    The reason to allow references to be initialized by non-lvalues was to allow the distinction between call-by-value and call-by-reference to be a detail specified by the called function and of no interest to the caller. For const references, this is possible, for non-const references it is not. For Release 2.0 the definition of C++ was changed to reflect this.

    In C++ 2.0 (and in ISO C++) temporaries can only be bound to const references.