Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is valid in C++, but a source for many bugs and sleepless nights. I think the C# guys decided that it's better to throw a warning/error since it's, in the vast majority of cases, a bug rather than something the coder actually want.</p> <p><a href="http://blogs.msdn.com/samng/archive/2007/11/09/local-variable-scoping-in-c.aspx" rel="nofollow noreferrer">Here</a>'s an interesting discussion on what parts of the specification this error comes from.</p> <p>EDIT (some examples) -----</p> <p>In C++, the following is valid (and it doesn't really matter if the outer declaration is before or after the inner scope, it will just be more interesting and bug-prone if it's before).</p> <pre><code>void foo(int a) { int count = 0; for(int i = 0; i &lt; a; ++i) { int count *= i; } return count; } </code></pre> <p>Now imagine the function being a few lines longer and it might be easy to not spot the error. The compiler never complains (not it the old days, not sure about newer versions of C++), and the function always returns 0.</p> <p>The behaivour is clearly a bug, so it would be good if a c++-lint program or the compiler points this out. If it's not a bug it is easy to work around it by just renaming the inner variable.</p> <p>To add insult to injury I remember that GCC and VS6 had different opinions on where the counter variable in for loops belonged. One said it belonged to the outer scope and the other said it didn't. A bit annoying to work on cross-platform code. Let me give you yet another example to keep my line count up.</p> <pre><code>for(int i = 0; i &lt; 1000; ++i) { if(array[i] &gt; 100) break; } printf("The first very large value in the array exists at %d\n", i); </code></pre> <p>This code worked in VS6 IIRC and not in GCC. Anyway, C# has cleaned up a few things, which is good.</p>
 

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