Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Для новичков > Вопрос по switch case


Автор: yngwie19 4.5.2009, 08:30
Здравствуйте объясните почему когда пишем:
Код

case WM_PAINT:
            
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd,&ps);
                    
    EndPaint(hwnd,&ps);
            
    return 0;

то компилятор ругается: 

error C2360: initialization of 'hdc' is skipped by 'case' label
see declaration of 'hdc'

initialization of 'hdc' is skipped by 'default' label
 see declaration of 'hdc'

а когда со скобками то все нормально
Код

case WM_PAINT:
{            
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd,&ps);
                    
    EndPaint(hwnd,&ps);
}            
    return 0;


Почему без скобок не хочет инициализировать созданную переменную?

Автор: Lazin 4.5.2009, 08:38
потому-что RTFM smile 

Автор: azesmcar 4.5.2009, 08:40
http://msdn.microsoft.com/en-us/library/61af7cx3(VS.71).aspx

Автор: yngwie19 4.5.2009, 09:11
Спасибо за ссылку но все же интересно почему вне блока {} нельзя ?

Автор: Lazin 4.5.2009, 09:21
Цитата(yngwie19 @  4.5.2009,  09:11 Найти цитируемый пост)
Спасибо за ссылку но все же интересно почему вне блока {} нельзя ?


Цитата(6.6.4)

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that
jumps(82) from a point where a local variable with automatic storage duration is not in scope to a point where it is in
scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).
Example:
Код

void f()
{
/ / ...
goto lx ; / / ill-formed: jump into scope of a
/ / ...
ly:
X a = 1;
/ / ...
lx:
goto ly ; / / OK, jump implies destructor
/ / call for a followed by construction
/ / again immediately following label ly
}

______________________________
(82) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.

Автор: azesmcar 4.5.2009, 09:30
yngwie19

Ошибка сама говорит, инициализация переменной пропущено меткой 'default'
например как вы предполагаете что будет работать вот этот код?
Код

int main()
{
    int c = 2;
    switch (c)
    {
    case 1:
        int x = 1;
    case 2:
        ++x;
    }
}

а если взять в {} то переменная обявленная в нем будет иметь локальную область видимости для блока заключенного в {}.
Код

int main()
{
    int c = 2;
    switch (c)
    {
    case 1:
        {
            int x = 1;
        }
    case 2:
        ++x; //тут ошибка, не видет переменную х
    }
}

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)