0

The issue of variable declaration in switch-case statements is well discussed in this SO post, and the answers covered most of the aspects. But I faced a problem for that I couldn't find a solid reason. Can someone please explain what is wrong with this code?

switch (var)
{
case 0:
    int test;
    test = 0;   // no error
    int test2 = 0;  // ERROR: initialization of 'test2' is skipped by 'case' label
    std::string str;
    str = "test";   // ERROR: initialization of 'str' is skipped by 'case' label
    break;
case 1:;
    break;
}

I know why the 6th line results in error. But what is wrong with the next two lines? I think this may have something to do with the difference between native types and class types, but I am not sure.

This is not a duplicate question of Why can't variables be declared in a switch statement?! As I have provided a link to the original one. Please read the two questions and note the difference. AFAIK, issue is not discussed in the original question.

Community
  • 1
  • 1
polfosol ఠ_ఠ
  • 1,840
  • 26
  • 41

1 Answers1

1

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps 90 from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

([stmt.dcl]/3)

The intuitive explanation is that you can only skip a declaration if the initialization it performs is effectively a no-op. If a value is provided, you can't skip it. If there is any code in the constructor of a class, you can't skip it.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • So can I conclude that if there is no code in a constructor of a class, my code wouldn't give any error? – polfosol ఠ_ఠ Jul 13 '16 at 05:43
  • @polfosol To be precise, the default constructor and destructor need to be "trivial", as the standard says. See http://en.cppreference.com/w/cpp/language/destructor#Trivial_destructor and http://en.cppreference.com/w/cpp/language/default_constructor#Trivial_default_constructor – Brian Bi Jul 13 '16 at 05:44