home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 32,548 of 33,346   
   Edson Manoel to All   
   Initializing a shadowing variable with t   
   19 Sep 12 14:41:28   
   
   From: e.tadeu@googlemail.com   
      
   { Please limit your text to fit within 80 columns, preferably around 70,   
     so that readers don't have to scroll horizontally to read each line.   
     This article has been reformatted manually by the moderator. -mod }   
      
   Hi!   
      
     In C++, it is usual to create a variable that shadows another variable   
   that exists in an outer scope:   
      
       int x = 10;   
       {   
           cout << "x: " << x << endl;   
      
           int x = 20;   
      
           cout << "x: " << x << endl;   
       }   
      
     This will print:   
      
       x: 10   
       x: 20   
      
      
     So far, so good, but there is a complication when the initialization   
   of the variable in the inner scope tries to use the variable in the   
   outer scope:   
      
       int x = 10;   
       {   
           int y = x + 1;   
      
           cout << "y: " << y << endl;   
      
           int x = x + 1;   
      
           cout << "x: " << x << endl;   
       }   
      
     This will print:   
      
       y: 11   
       x:    
      
      
     What happens is that the inner 'x' variable is using *itself* in its   
   own initialization (and using itself in an uninitialized state, i.e.,   
   garbage data). This is one of the C++ "bizarre" things, and seems very   
   error-prone.   
      
     I would like to know if the standard says something about this   
   situation... is the behaviour clearly defined, or is it one of the   
   "implementation defined" or "unspecified" things?   
      
   Thanks!   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca