TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: NEIL HELLER
from: BALOG PAL
date: 1997-08-26 07:05:00
subject: Why the braces?

                              Hi, Neil Heller!
On 23 Aug 97  10:59:00 you wrote to All
 NH> I always thought that one of the features of C++ is that variables
 NH> can be declared ANYWHERE (such as near where you're going to use them).
That's close true.
 NH> However I ran across a situation in MSVC 1.6 with a CPP module that
1.6?  Do you really have that version? I thousght MS stopped the 16 bit
compiler line at 1.52.
 NH> seems to contradict this.  Can someone explain to me why?
 NH> If I write a switch statement thusly, I get compiler errors:
Yes, you should get them.
 NH> switch (foo) {
 NH>   case 1 :
 NH>     int bar = 2;
 NH>     break;
 NH>   case 2 :
 NH>     int bar = 3;
 NH>     break;
 NH> }
You must get a "bar: redefinition" at line 6. You must not define two objects
with identical name to the same scope. And in the above example you did that.
This is the same as if in a C program you write
int main()
{
   int i;
   int i;   // error here: i already defined
   return 0;
}
 NH> However, if I write the code this way there are no errors:
 NH> switch (foo) {
 NH> case 1 : {
 NH>   int bar = 2;
 NH>   break;
 NH>   }
 NH> case 2 : {
 NH>   int bar = 3;
 NH>   break;
 NH>   }
 NH> }
Here you scoped both "bar" variables. So they are tho distinct local
variables that disappear at the closing } together with their value.
 NH> I was under the assumption that the braces weren't necessary in C++ as
 NH> far as declaring variables is concerned.  Why then do I need the
 NH> braces?  Do the added braces affect portability in any way?
Braces have nothing with portability. They define block of execution and also
controls lifetime and visibility of objects. Inserting them will in general
produce totally different code.
Paul
... SENILE.COM found . . . Out Of Memory . . .
--- OS/2 Warp
---------------
* Origin: The FlintStones' Cave in BedRock (2:371/20)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.