unordered_map - Seemingly Random Control Jumps

*** Not intended for practical use, just trying to understand why this issue occurs ***

There are seemingly random control jumps in this program.

After the lines:

1
2
umap["FirstKey "]  = 1;
umap["SecondKey"]  = 2;

Control jumps to the last line in my program (line 12).

And then at the start of the for loop, control jumps to the penultimate line (line 11).

Why does this happen?

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
	std::unordered_map<std::string, short int> umap;

	umap["FirstKey "]  = 1;
	umap["SecondKey"]  = 2;

	for (auto x : umap)
		std::cout << "Key Value: " << x.first << "  |  "
                << "Mapped Value: " << x.second << std::endl;
}
Last edited on
> Why does this happen?
It's an artefact of using modern optimising compilers.

1. A for loop can execute zero times.
2. Some compilers move the condition to the end of the loop.

This does result in some visual weirdness when single stepping the code, as not all the instructions for a line of code are necessarily contiguous in the assembler.

Plus your for loop lacks any braces, so the last line of your loop is also the last line of your program.

Try it with say
1
2
3
4
5
	for (auto x : umap) {
		std::cout << "Key Value: " << x.first << "  |  "
                << "Mapped Value: " << x.second << std::endl;
	}
	std::cout << "All done" << std::endl;
Thanks for that salem c
Topic archived. No new replies allowed.