Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error C2360: Initialization of 'hdc' is skipped by 'case' label

Where is the huge difference, which generates error C2360, in 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;
}
like image 876
Cubi73 Avatar asked Nov 24 '13 17:11

Cubi73


2 Answers

The first is legal and the second isn't. Skipping a declaration without an initializer is sometimes allowed, but never one with an initializer.

See Storage allocation of local variables inside a block in c++.

like image 142
Alan Stokes Avatar answered Oct 21 '22 09:10

Alan Stokes


When a variable is declared in one case, the next case is technically still in the same scope so you could reference it there but if you hit that case without hitting this one first you would end up calling an uninitialised variable. This error prevents that.

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

switch (msg) {
    case WM_PAINT:
    {
        HDC hdc;
        hdc = BeginPaint(hWnd, &ps);
    } 
    break;
}
like image 6
Leninkumar Avatar answered Oct 21 '22 09:10

Leninkumar