TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: NEIL HELLER
from: IDO RAZON
date: 1997-08-30 16:22:00
subject: Why the braces?

   Neil Heller, All, 23 Aug 97, 08:59 
 NH> If I write a switch statement thusly, I get compiler errors:
 NH> switch (foo) {
 NH>     case 1 :
 NH>         int bar = 2;
 NH>         break;
 NH>     case 2 :
 NH>         int bar = 3;
 NH>         break;
 NH> }
 Your mistake here is assuming that the different code fragments for
different cases in `switch' behave like seperate blocks. In reality, all
fragments belong to the same code, and `switch' can be thought of as a
`goto' statement with the different `case' statements acting as labels.
 So, in reality, the code you wrote looks something like:
 {
    if (foo == 1)
      goto L1;
    if (foo == 2)
      goto L2;
    goto L3;
  L1:
    int bar = 1;
    goto L3;
  L2:
    int bar = 2;
  L3:
 }
 I hope you realize that this code is illegal, because it tries to define
the variable `bar' twice within the same block. Therefore, your compiler
errors weren't for the declaration of `bar', but for its RE-declaration
within the same block.
 Hope this helps,
       - Ido
---
---------------
* Origin: Ido. Pronounced ee-DO. (2:403/409.42)

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™.