🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: net.lang.c
Article #9265

references - C++

#9265
From: Andrew Koenig
Date: Sat, 06 Sep 1986 21:23
51 lines
2239 bytes
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 */
Technical Details
Message-ID: <6027@alice.uUCp>
Path: arc1-ca.pugleaf.net!utzoo!mnetor!seismo!caip!princeton!allegra!alice!ark

Show Full Headers
Complete Article Headers
Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: arc1-ca.pugleaf.net!utzoo!mnetor!seismo!caip!princeton!allegra!alice!ark
From: ark@alice.UucP (Andrew Koenig)
Newsgroups: net.lang.c
Subject: references - C++
Message-ID: <6027@alice.uUCp>
Date: Sat, 6-Sep-86 17:23:06 EDT
Article-I.D.: alice.6027
Posted: Sat Sep  6 17:23:06 1986
Date-Received: Sat, 6-Sep-86 23:47:07 EDT
Organization: Bell Labs, Murray Hill
Lines: 51