Error C2360: Initialization of "hdc" is skipped by the label "case"

Where is the huge difference that generates error C2360 in the following two definitions?

switch (msg) { case WM_PAINT: HDC hdc; hdc = BeginPaint(hWnd, &ps); // No error break; } 

and

 switch (msg) { case WM_PAINT: HDC hdc = BeginPaint(hWnd, &ps); // Error break; } 
+7
c ++ switch-statement winapi
source share
2 answers

The first is legal, and the second is not. Skipping a declaration without an initializer is sometimes allowed, but never performed with an initializer.

See Distribution of storage of local variables inside a block in C ++ .

+9
source share

When a variable is declared in one case, the next case technically remains in the same scope, so you can reference it there, but if you click on this case without hitting it first, you will end up calling an uninitialized variable. This error prevents this.

All you have to do is either define it before the switch statement, or use curly braces {} to make sure that it goes out of scope before exiting a specific case.

switch (msg) {case WM_PAINT: {HDC hdc; hdc = BeginPaint (hWnd, & ps); }

0
source share

All Articles