references - C++

Andrew Koenig ark at alice.UucP
Sun Sep 7 07:23:06 AEST 1986

Karl W. Z. Heuer writes:

> BMS-AT!stuart writes:
> >[re the declaration of reference types "foo(char &c)"]
> >I don't like this.  It violates the nice consistent way that C expressions
> >work.  'char *c' means that '*c' is of type char.  '&c' is not of type
> >char in any other context.
> I am also somewhat uneasy about calling it "char &c".  The consistent way to
> declare it would be "char *&c", since you have to write "&c" to get ahold of
> the "char *" object you are really using.

Bjarne Stroustrup made a comment on this about the way C++ does
things, but I suspect his remark is a little too abbreviated for
people not familiar with C++.  Here is some more detail:

In C++ one can declare a reference using the & declarator operator
in much the same way as one can declare a pointer using the * declarator
operator.  There is one big difference:  a reference MUST always be
initialized at the time it is declared.  Thus, I can write:

	char c;
	char &cr = c;
	char *cp = &c;

The first example declares a character.  No problem there.  The third
declares a character pointer and initializes it to the address of c.
No problem there either.  The second line declares a character reference
named cr and makes it a synonym for c.  Thus, if I write

	*cp = '?';

that sets the value of c to '?'; and so does

	cr = '?';

You can see a few things from this example:

	1. A reference must always be initialized as it is delcared.

	2. Subsequent uses of the reference denote the object with
	   which the reference was initialized.

	3. Therefore, the initializer for a reference must be an lvalue.

In other words:

	char c;
	char &cr = c;		/* legal */
	char &cr;		/* illegal -- no initialization */
	char &cr = &c;		/* illegal -- &c is not an lvalue */

More information about the Comp.lang.c mailing list