3

AFAIK it is not a good idea to define objects in a case-label without being scoped (surrounded with curly-braces) because control can bypass their definition:

1-

char grade = 'C';

switch (grade){
case 'A':
    std::cout << "grade A" << '\n';
    int n_elem = 0; // 
break;
case 'B': //  error: jump to case label
    std::cout << "grade A" << '\n';
    n_elem = 100;
break;
}

2-

char grade = 'C';

switch (grade){
case 'A':
    std::cout << "grade A" << '\n';
    int n_elem; // declaration or definition
break;
case 'B':
    std::cout << "grade A" << '\n';
    n_elem = 100; // ok
break;
}
  • Why in 1 it doesn't work but in 2 it works?

  • Why in 1 n_elem mustn't have an initializer but in 2 n_elem can be default-initialized?

  • I guess in 1 and 2 n_elem is initialized what you think? Thank you!

Itachi Uchiwa
  • 3,044
  • 12
  • 26

0 Answers0