Quick Answer

Variable initialization across case labels

Understanding the Issue

This error occurs when trying to jump past a variable initialization in a switch statement, which would skip the constructor call.

The Problem

This code demonstrates the issue:

Cpp Error
// Problem: Cross initialization
switch (val) {
    case 1: string s = "hello"; break;
    case 2: s = "world"; // Error
}

The Solution

Here's the corrected code:

Cpp Fixed
// Solution 1: Enclose in scope
case 1: { string s = "hello"; break; }

// Solution 2: Declare before switch
string s;
switch (val) {
    case 1: s = "hello"; break;
    case 2: s = "world"; break;
}

Key Takeaways

Use blocks to limit variable scope in switch cases.