Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem is that variables declared in one <code>case</code> are still visible in the subsequent <code>case</code>s unless an explicit <code>{ }</code> block is used, <em>but they will not be initialized</em> because the initialization code belongs to another <code>case</code>.</p> <p>In the following code, if <code>foo</code> equals 1, everything is ok, but if it equals 2, we'll accidentally use the <code>i</code> variable which does exist but probably contains garbage.</p> <pre><code>switch(foo) { case 1: int i = 42; // i exists all the way to the end of the switch dostuff(i); break; case 2: dostuff(i*2); // i is *also* in scope here, but is not initialized! } </code></pre> <p>Wrapping the case in an explicit block solves the problem:</p> <pre><code>switch(foo) { case 1: { int i = 42; // i only exists within the { } dostuff(i); break; } case 2: dostuff(123); // Now you cannot use i accidentally } </code></pre> <h2>Edit</h2> <p>To further elaborate, <code>switch</code> statements are just a particularly fancy kind of a <code>goto</code>. Here's an analoguous piece of code exhibiting the same issue but using a <code>goto</code> instead of a <code>switch</code>:</p> <pre><code>int main() { if(rand() % 2) // Toss a coin goto end; int i = 42; end: // We either skipped the declaration of i or not, // but either way the variable i exists here, because // variable scopes are resolved at compile time. // Whether the *initialization* code was run, though, // depends on whether rand returned 0 or 1. std::cout &lt;&lt; i; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload