interpret.cpp: In function ‘int main(int, char**)’:
interpret.cpp:50:3: error: jump to case label
interpret.cpp:34:20: error: crosses initialization of ‘std::ifstream script’
switch(argc)
{
//...
case 2:
ifstream script(argv[1]); // <- 'script' constructed here
//...
break;
default:
// 'script' still in scope here, but not constructed here
//...
} // 'script' destructed here
If the 'default' label is taken... 'script' will still be in scope for the 'default' section of code. However the program will have jumped passed the line where it was constructed, meaning you'd have access to an object that was not properly constructed. This is extremely dangerous!
Furthermore, 'script' will be destructed at the end of the switch statement. Trying to destruct something that was never constructed is also extremely dangerous and would likely cause the program to crash if it were allowed.
To fix you need to restrict where the object is constructed:
1 2 3 4 5 6 7 8 9
case 2:
{ // <- limits scope of script
ifstream script(argv[1]); // <- 'script' constructed here
//...
break;
} // <- now it will be destructed here
default:
// no longer in scope here, so no error
If it interests anyone, here is what I gathered from a little "googling".
Switch statements are just labels that instructs the compiler to jump to a particular part of code during execution, therefore all the variables not withtin {} belong to the scope of the function inside which the switch statement resides.
i.e., during the construction of a symbol table, the variables not in {} get declared with the scope as the entire function (or outer scope), and it should ideally have definition in the same scope.
However, the definition of the variable happens in the second run of compiling, i.e., after the symtab has already been constructed.
The code that defines the variable is within the bunch of statements after the case label but before the next label, which is why the variables get declared but not defined.
I'd appreciate it if anyone could point out something missing in what I've understood!