Hi Neil,
You asked:
NH>I always thought that one of the features of C++ is that variables can
NH>be declared ANYWHERE (such as near where you're going to use them).
NH>However I ran across a situation in MSVC 1.6 with a CPP module that
NH>seems to contradict this. Can someone explain to me why?
I'll try
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>}
The errors are because you have two declarations for the same variable
in the same scope
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 however each is in it's own scope.
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?
The scope of the variable is the enclosing braces, you can only
declare it once within a scope, and it is invalid outside the scope.
George
* SLMR 2.1a * Computers eliminate spare time.
--- Maximus/2 3.01
---------------
* Origin: DoNoR/2,Woking UK (44-1483-725167) (2:440/4)
|