Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 491
Destructor Avatar asked Dec 04 '14 08:12

Destructor


1 Answers

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.

like image 156
Jonathan Wakely Avatar answered Sep 17 '22 08:09

Jonathan Wakely