jeudi 28 octobre 2021

C++11 is not executing switch correctly when variable is declared in case block

Consider the snippet below. If I compile this with GCC/C++11 then I expect that if I call this with e.g. var=2 that that block is executed. Anyway I expect at least one of the 3 switch blocks are called.

However what I get is only the "start" and "end" lines. So this switch block is not working: even "default" is not called. I even did not believe GDB when I saw this!

The root cause of this is the variable declaration in case block 1 (int anotherVar). To fix this problem I need to add brackets around case 1 (own scope) or decl the variable in the constructor body at the top.

My Questions are:

  • Why is this happening? What is the technical reason? If this is not happening in all situations, then in which situations can this happen?
  • Is there a compiler error/warning flag for this?
MyClass::MyClass(int var) { 
   std::cout << "Constructor start" << std::endl;
   switch (var) {
     case 1:
       std::cout << "Case 1 executed" << std::endl;
       int anotherVar = doSomething();
     case 2:
       std::cout << "Case 2 executed" <<std::endl;
     break;
     default:
       std:cout << "Default executed" << std::endl;
   }
   std::cout << "Constructor ended" << std::endl;
}`

This outputs when called with var=2:

Constructor start
Constructor ended

Aucun commentaire:

Enregistrer un commentaire