Transfer of control bypasses initalization of variable with ifstream

Can anyone explain why this doesn't work?

1
2
3
4
5
6
7
8
9
10
switch (level) {
case Forest:
	const std::ifstream map("assets/forest.map");
	break;
case Desert:
	const std::ifstream map("assets/desert.map");
	break;
default:
	break;
}


^ This throws an error: Transfer of control bypasses initalization of variable "map".

This will as well throw an error on the next section of code:

1
2
3
4
if (map.fail()) {
	std::cout << "Unable to load the map file." << std::endl;
	tilesLoaded = false;
}


Where the error will be: Identifier "map" is undefined.

Any help please?
Last edited on
The individual sections of a switch statement are actually all one block. They're not isolated from each other. As the compiler tells you flat-out, if you were to jump to Desert, you would jump over the initialization of the map in the Forest section. That's a problem.

Not only that, but none of those would be visible outside of the switch statement. You'll probably want to declare map outside of your switch statement.

-Albatross
I see @Albatross, thank you. Do you mind dropping an example of how would one define the ifstream outside the switch block, and later give the ability to the switchblock to change the map?
Last edited on
As Albatross said, you need to declare the ifstream before the switch and use the .open() method to open the files. Also, you can't make the ifstream const or it won't be usable since it needs to be able to modify itself (file position pointers, buffers, etc) to operate.

1
2
3
4
5
6
    std::ifstream map;
    switch (level) {
    case Forest: map.open("assets/forest.map"); break;
    case Desert: map.open("assets/desert.map"); break;
    default: /* presumably an error */ break;
    }

Thank you @dutch! That worked. I had no idea that one one could use map.open.
Last edited on
Topic archived. No new replies allowed.