[comp.lang.c++] casts and references in C++

schmidt@crimee.ics.uci.edu (Doug Schmidt) (05/29/90)

Hi,

  The following program illustrates an inconsistency between g++ and
cfront in their handling of references.  I am curious to know which
compiler gets it ``right.''

----------------------------------------
extern "C" char *puts (char *s);

char **lookup (char **p) { return p; }

void foo (char **ptr)
{
  char *&t0 = (char *&) *lookup (ptr);
  char *&t1 = (char *) *lookup (ptr);

  if (&t0 == ptr)
    puts ("I get printed with both g++ and cfront 2.0.");
  if (&t1 == ptr)
    puts ("I get printed with g++ but *not* with cfront 2.0.");
}

main ()
{
  char *p;

  foo (&p);
}
----------------------------------------

If you compile and execute this with g++ 1.37.2 you get:

----------------------------------------
% g++ test.c
% a.out
I get printed with both g++ and cfront 2.0.
I get printed with g++ but *not* with cfront 2.0.
----------------------------------------

On the other hand, if you compile with cfront 2.0 you get

----------------------------------------
% CC test.c
% a.out
I get printed with both g++ and cfront 2.0.
----------------------------------------

Examining the generated C code from cfront shows why:

----------------------------------------
char foo__FPPc (__0ptr )char **__0ptr ;
{
  char **__1t0 ;
  char **__1t1 ;
  char *__0__I1 ;

  __1t0 = (((char **)lookup__FPPc ( __0ptr ) ));
  __1t1 = ( (__0__I1 = (((char *)((*lookup__FPPc ( __0ptr ) ))))), (& __0__I1 )) ;
  if ((__1t0 )== __0ptr )
    puts ("I get printed with both g++ and cfront 2.0.");
  if ((__1t1 )== __0ptr )
    puts ("I get printed with g++ but *not* with cfront 2.0.");
}
----------------------------------------

It seems to me that cfront is correct here, and that g++ is
incorrectly optimizing away the temporary variable.  Does anyone have
a quote from the C++ ref manual that either affirms or denies this
claim?

  thanks,

    Doug
--
=========================================================================
SCIENCE does not remove the TERROR of the GODS -- Rev. J.R. ``Bob'' Dobbs
=========================================================================
schmidt@ics.uci.edu (ARPA) | office: (714) 856-4043

paul@gill.UUCP (Paul Nordstrom) (06/05/90)

In article <2661674A.8793@paris.ics.uci.edu> schmidt@crimee.ics.uci.edu (Doug Schmidt) writes:
>Hi,
>
>  The following program illustrates an inconsistency between g++ and
>cfront in their handling of references.  I am curious to know which
>compiler gets it ``right.''
>

>    Doug
>--
>schmidt@ics.uci.edu (ARPA) | office: (714) 856-4043


And if you compile it with Oregon C++ 2.0 you get:

/tmp % occ x.c -o x
/tmp % ./x
I get printed with g++ but *not* with cfront 2.0.
/tmp %

Now all we need is a compiler that prints neither!  :-)  Maybe Zortech or TC++. :-)


-- 
Paul Nordstrom
Gill & Co., L.P.
uunet!gill!paul