views:

89

answers:

3

ok well i have structure

struct balls {
    balls(UINT_PTR const &val) : BALL_ID(val){}
    int Ex;
    int Ey;
    const UINT_PTR BALL_ID;
};
balls ball1(0x1);

and i have a switch statement

switch(wParam)
        {
        case ball1.BALL_ID:
                if(ball1.Ex<300)
                {
                    ball1.Ex++;
                }
                else
                {
                    KillTimer(hWnd, ball1.BALL_ID);
                }
                InvalidateRect(hWnd, rect, false);
                break;
        case SCORECOUNTER_ID:
                if(life==0)
                {
                    if(scorecounter<1000)
                    {
                        scorecounter+=100;
                        _swprintf(str, _T("Score: %d"), scorecounter);
                        InvalidateRect(hWnd, rect, false);
                    }
                    else
                    {
                        _swprintf(level, _T("Level: %d"), 2);
                        InvalidateRect(hWnd, rect, false);
                    }
                }
            break;
        }

i get an error thatball1.BALL_ID is not constant the second line should solved this but it didn't any idea?

+3  A: 

The case labels must be integral constant expressions -- they must be evaluable during translation (i.e. at compile). In this case, BALL_ID cannot be evaluated at compile-time. Different ball objects are allowed to have different BALL_ID values, hence the compiler cannot possibly evaluate it during translation. Futher, the . (member resolution operator for objects) cannot be used in a case label (i.e. even if you did make BALL_ID static it wouldn't work for you).

I would hazard a guess that SCORECOUNTER_ID is a macro/static const int and is hence evaluable by the compiler.

You can use a namespace scope enum or int to fix this. E.g:

struct s {
 s(const int t) : x(t) {}
 const int x;
};

namespace s2 {
 const int val = 42;
}

int main() {
 s ss(4);
 int val = 42;
 switch (val) {
  case s2::val:
  break;
  }
}
dirkgently
well how can i fix it?
Ramiz Toma
using if(), probably.
Mart Oruaas
... why yes of course, until and unless the OP needs to stick to the `switch`!
dirkgently
A: 

case labels have to be known at compile time (the underlying assumption is that a switch is implemented more efficiently than a sequence of ifs knowing the values at compile time, using a jump table for instance). const is needed but not sufficient for that. ball.BALL_ID is something const which isn't known at compile time, so can't be a case label.

AProgrammer
A: 

Not every constant variable of an integral type is a constant expression. The case label of the switch statement requires a constant expression.

celavek