Connecting Tech Pros Worldwide Help | Site Map

surprised that this is valid...

  #1  
Old March 18th, 2008, 06:26 PM
werasm
Guest
 
Posts: n/a
Hi all,

I've per chance noticed that this code compiles without warnings:

struct x
{
x(): y_( y_ ){}

int y_;
};

I've used gcc 4.1.0, comeau online and all compilers available at
dinkumware online.

Are there cases where similar code (a member initialising itself with
itself) would make sense? I was surprised when I discovered this.

Regards,

Werner
  #2  
Old March 18th, 2008, 11:35 PM
Greg Herlihy
Guest
 
Posts: n/a

re: surprised that this is valid...


On Mar 18, 11:14*am, "jason.cipri...@gmail.com"
<jason.cipri...@gmail.comwrote:
Quote:
Note that if there is an x or a y (or in your case a y_) in a larger
scope, then it will use the larger scoped one instead:
>
int x = 0, y = 0;
>
void function () {
* int x(x); // now it uses x from above
* int y = y; // same here
>
}
No, both x and y are still being initialized with their own
indeterminate values - the x and y declarations in the outer scope
make no difference here. In short, the inner x and y declarations hide
the outer ones.

There is one notable exception, however:

const int i = 2;
{
int i[i];
}

In this case, the inner "i" declares an array of two ints.

Greg

  #3  
Old March 19th, 2008, 12:26 AM
jason.cipriani@gmail.com
Guest
 
Posts: n/a

re: surprised that this is valid...


On Mar 18, 6:26 pm, Greg Herlihy <gre...@mac.comwrote:
Quote:
On Mar 18, 11:14 am, "jason.cipri...@gmail.com"
>
<jason.cipri...@gmail.comwrote:
Quote:
Note that if there is an x or a y (or in your case a y_) in a larger
scope, then it will use the larger scoped one instead:
>
Quote:
int x = 0, y = 0;
>
Quote:
void function () {
int x(x); // now it uses x from above
int y = y; // same here
>
Quote:
}
>
No, both x and y are still being initialized with their own
indeterminate values - the x and y declarations in the outer scope
make no difference here. In short, the inner x and y declarations hide
the outer ones.
Oops, thanks for catching that, Greg.
Quote:
There is one notable exception, however:
>
const int i = 2;
{
int i[i];
}
>
In this case, the inner "i" declares an array of two ints.
>
Greg
Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
Is these functions C90 and/or C99 ? Bernard answers 3 November 14th, 2005 09:37 AM
typdef'ing from sig_atomic_t valid? Mark Piffer answers 21 November 14th, 2005 06:22 AM
Is this standard stewart.tootill@softel.co.uk answers 3 July 23rd, 2005 04:58 AM
Why doesn't this modify the pointer? Markus Dehmann answers 4 July 23rd, 2005 01:59 AM