surprised that this is valid...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • werasm

    surprised that this is valid...

    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
  • Greg Herlihy

    #2
    Re: surprised that this is valid...

    On Mar 18, 11:14 am, "jason.cipri... @gmail.com"
    <jason.cipri... @gmail.comwrote :
    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

    Comment

    • jason.cipriani@gmail.com

      #3
      Re: surprised that this is valid...

      On Mar 18, 6:26 pm, Greg Herlihy <gre...@mac.com wrote:
      On Mar 18, 11:14 am, "jason.cipri... @gmail.com"
      >
      <jason.cipri... @gmail.comwrote :
      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.
      Oops, thanks for catching that, Greg.
      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

      Comment

      Working...