Re: 'case' requires a constant?
You didn't note how many "cases" you have, but I typically do this sort of
thing with an if/else if list. Remember to have a "else" at the end that
catches the ones that don't match anything in your list. At the end of the
day I don't think this is a ton less efficient. And it's really the only
way to do a "sort of" switch when the data could be variable.
Another idea (if the values really don't change) is to create an enum with
the values and use that in the switch.
Tom
"Robby" <Robby@discussions.microsoft.com> wrote in message
news:9F7FC367-AFCA-47EA-BA06-F9CE066984BF@microsoft.com...
Hello,
The following code generates the following error:
c:\_DTS_PROGRAMMING\C_PROGRAMMING\vc++\MY_APPS_LAB\XPPLC\WndProc_CW1.cpp(315):
error C2051: case expression not constant
If a value comming from an array that has been defined as below, well,
shouldn't that valuie be constant by default.... I guess not!
The error points to the following line in the code below:
case (WindowButtons[0].CW1_btC_ID): //if equals the exit button
Here is the code:
======================================WndProc_CW1.h
struct hdCW1_WindowButtonsTAG
{
int iCTL_idx;
TCHAR *szCW1_btC_Name;
int CW1_btC_RectLeft;
int CW1_btC_RectTop;
int CW1_btC_RectRight;
int CW1_btC_RectBottom;
int CW1_btC_ID;
};
====================================================
========================================WndProc_CW1.cpp
#include <windows.h>
#include "WndProc_CW1.h" //Default header file
LRESULT CALLBACK WndProc_CW1 (HWND hwnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
//ARRAY declaration
hdCW1_WindowButtonsTAG WindowButtons[] =
{
1,TEXT("< EXIT >"),580,350,80,40,1,
2,TEXT("SEND BYTES rs232 >"),10,5,180,30,2,
3,TEXT("READ BYTES rs232 >"),20,30,40,50,3,
};
static HWND hdCW1_WindowButtons[3]; //Current 3 window buttons
switch(message)
{
... other code...
case WM_CREATE:
//CREATES MAIN WINDOW BUTTON CONTROLS
for(i=0;i<3;i++)
{
hdCW1_WindowButtons[i] = CreateWindow(
TEXT ("button"),WindowButtons[i].szCW1_btC_Name,
WS_CHILD | WS_VISIBLE |BS_PUSHBUTTON ,
WindowButtons[i].CW1_btC_RectLeft,
WindowButtons[i].CW1_btC_RectTop,
WindowButtons[i].CW1_btC_RectRight,
WindowButtons[i].CW1_btC_RectBottom,
hwnd,(HMENU)WindowButtons[i].CW1_btC_ID,
(HINSTANCE) GetWindowLong(hwnd,GWL_HINSTANCE),NULL);
}
return 0;
case WM_COMMAND:
switch (LOWORD(wParam))
{
//error happens because of the next line !
case (WindowButtons[0].CW1_btC_ID): //if equals the exit button
DestroyWindow(hwnd);
break;
...other code....
}
===================================================
I can probably do it with an 'if' statement as opposed to doing it by a
case
statement. However, I would like to know why I get a 'constant' error.
Is it because I must declare the structure and array as constant?
Just asking!
Thankyou for any feedback on this!
--
regards
Robert