[gnu.g++.bug] hard bug

tiemann@ai.mit.edu (Micheal Tiemann) (01/12/90)

Here's a C++ teaser.  What's wrong with the following code?

    extern "C" void printf (char *, ...);
    struct X
    {
      int x;

      X (int i) { x = i; }
      ~X () { printf ("destroying object %d\n", x); }
    };

    main ()
    {
      int i = foo ();

      if (i)
	for (X x(5); i < 10; i++)
	  {
	    printf ("loop count = %d\n", i);
	  }
      Greyhawk:
	;
    }

    int foo () { return 0; }

More precisely, when execution reaches Greyhawk,

	1.  Is `x' in scope?
	2.  If so, it is initialized?
	3.  Where and when is `x' destroyed?

If the scope of `x' were limited to the scope of the for loop, none of
these problems would be "interesting", and everything work work as one
might expect.

Michael

scp@BLANCHE.ACL.LANL.GOV (Stephen C. Pope) (01/12/90)

on Thu, 11 Jan 90 14:53:07 EST,
tiemann@ai.mit.edu (Micheal Tiemann) said:

Micheal> Here's a C++ teaser.  What's wrong with the following code?

[ ... ]

Micheal> More precisely, when execution reaches Greyhawk,

Micheal> 	1.  Is `x' in scope?
Micheal> 	2.  If so, it is initialized?
Micheal> 	3.  Where and when is `x' destroyed?

Micheal> If the scope of `x' were limited to the scope of the for loop, none of
Micheal> these problems would be "interesting", and everything work work as one
Micheal> might expect.

That's one solution.  I'm always annoyed when I get bitten by my habit of
writing:

	for( int i = 0; i < stopval; ++i )

only to discover that i was defined in the previous for loop.


However, it seems to me that one would be better served to
consider:

	if( expr )
		simple_statement;
       [else
		simple_statement;]

to be equivalent to:

	if( expr )
	    {
		simple_statement;
	    }
       [else
	    {
		simple_statement;
	    }]

In this way, *any* definition is local to the if statement (the
block enclosing the if clause or the else clause).

By keeping the loop control variable of the for loop around
after the termination of the for loop seems pretty handy to avoid
things like assigning to a variable or an object of more
comprehensive scope as the last part of the loop body
before testing and exiting so that information can be passed out
of the loop body.  Of course, this can also be done by giving
the loop control object (or whatever else it might be) more
comprehensive scope, which is what I think you want to argue for.

Micheal> Michael

stephen pope
advanced computing lab - lanl
scp@acl.lanl.gov