10

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;
}
bobobobo
  • 64,917
  • 62
  • 258
  • 363
Cubi73
  • 1,891
  • 3
  • 31
  • 52

2 Answers2

10

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++.

Community
  • 1
  • 1
Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
  • 1
    Is there a better way to initialize hdc? – Cubi73 Nov 25 '13 at 07:31
  • 1
    Put the whole block in braces as Hans said - the issue is the scope. Better still move it out to a separate method, or it's easy to end up with a switch statement of several hundred lines. – Alan Stokes Nov 25 '13 at 08:26
6

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;
}
Laurie Stearn
  • 959
  • 1
  • 13
  • 34
Leninkumar
  • 314
  • 3
  • 3