references - C++

Andrew Koenig ark at alice.UucP
Wed Sep 10 00:08:40 AEST 1986

Apparently I caught whatever was affecting Bjarne when he posted his
original note about references.  Sigh.  I'll try again.

Sam Kendall is right -- if you initialize a reference with something
that isn't an lvalue then the reference refers to a temporary.  Thus:

	char c;
	char &cr;		/* illegal -- no initialization */
	char &cr = c;		/* legal */
	char &cr = 'a';		/* equivalent to:  char temp='a'; char &cr=temp; */
	char &cr = &c;		/* illegal -- &c is not a char */

Sam is also right in saying that initializers do not have to be
explicitly provided for references declared as formal parameters.
This is indeed because the initializers will appear whenever the
function is called.  Thus:

	void zap (int& x) { x = 0; }

	int z;
	zap (z);		/* sets z to 0 */


	double d;
	zap (d);		/* illegal -- d is the wrong type */
	zap ((int) d);		/* sets a copy of the integer value
				   of d to 0.  Essentially no effect */

More information about the Comp.lang.c mailing list