error C2360: initialization of 'hPen' is skipped by 'case' label的解决方法

时间:2022-08-10 19:48:30

在写一个绘制正弦曲线的windows程序时,遇到这个问题。

程序代码如下:

LRESULT __stdcall WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)

{

#define SEGMENTS 500  // 取的点数(在一个周期内取500个点)

#define PI 3.1415926  // 圆周率

 

    HDC hdc;

    PAINTSTRUCT ps;

    RECT rt;

    int cxClient, cyClient;

    POINT pt[SEGMENTS];

    int i;

   

    switch(message)

    {

    case WM_PAINT:

        hdc = ::BeginPaint(hWnd, &ps);

        ::GetClientRect(hWnd, &rt);

        cxClient = rt.right - rt.left;

        cyClient = rt.bottom - rt.top;

 HPEN hPen = ::CreatePen(PS_SOLID, 3, RGB(255, 0, 0));

 HPEN hOldPen = (HPEN)::SelectObject(hdc, hPen);

        // 画横坐标轴

        ::MoveToEx(hdc, 0, cyClient/2, NULL);

        ::LineTo(hdc, cxClient, cyClient/2);

        // 找出500个点的坐标

        for(i=0; i<SEGMENTS; i++)

        {

            pt[i].x = cxClient*i/SEGMENTS;

            pt[i].y = (int)((cyClient/2)*(1 - sin(2*PI*i/SEGMENTS)));

        }

        // 将各点连在一起

        ::Polyline(hdc, pt, SEGMENTS);

        ::EndPaint(hWnd, &ps);

        break;

    case WM_DESTROY:

        ::PostQuitMessage(0);

        break;

    }

    return ::DefWindowProc(hWnd, message, wParam, lParam);

}

运行程序出现如下错误:

D:/VC/MyProjects/Windows程序设计/配书代码/04SineWave/SineWave.cpp(100) : error C2360: initialization of 'hOldPen' is skipped by 'case' label

        D:/VC/MyProjects/Windows程序设计/配书代码/04SineWave/SineWave.cpp(85) : see declaration of 'hOldPen'

D:/VC/MyProjects/Windows程序设计/配书代码/04SineWave/SineWave.cpp(100) : error C2360: initialization of 'hPen' is skipped by 'case' label

        D:/VC/MyProjects/Windows程序设计/配书代码/04SineWave/SineWave.cpp(84) : see declaration of 'hPen'

原因是:

HPEN hPen; HPEN hOldPen;声明在case下面编译器会认为不安全, 因为case不是每次都会执行到。

解决方法:

1、  可以将HPEN hPen; HPEN hOldPen;switch case的前面声明,然后在里面定义。

2、  或者在case语句的后面加上大括号{}将所有语句括起来,如下:

switch(message)

    {

    case WM_PAINT:

        {

hdc = ::BeginPaint(hWnd, &ps);

……

HPEN hPen = ::CreatePen(PS_SOLID, 3, RGB(255, 0, 0));

HPEN hOldPen = (HPEN)::SelectObject(hdc, hPen);

            ……

          break;

  }

    case WM_DESTROY:

        ::PostQuitMessage(0);

        break;

    }