• Advertisement
Sign in to follow this  

static const not const in switch

This topic is 4644 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hello I have a class with static const attributes, for example: class foo { public: static const DWORD bar; } const DWORD foo::bar = 1; and now I want to use this constant in switch: switch .. case (foo::bar): <-- but it says here that case expression is not constant .. why? can I do sth to use such constants in case expression? my compiler is MSVC2003 Thanks

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
it works fine that error only comes up when theres no ; after the class def. Did you forget it?

Share this post


Link to post
Share on other sites
static/class members that are constant intergal types can be defined inside a class, this is very beneficial when doing meta-template programming [grin]


#include <cstddef>

struct foo {

typedef std::size_t size_type;

static const size_type bar = 30;

};

Share this post


Link to post
Share on other sites
no it's not ; , I just forgot about it.
when I have class consisting of 2 files:

"key.h"
class CKey
{
public:
int key;

static const int foo;
};
EOF

"key.cpp"
#include "Key.h"

const int CKey::foo = 1;
EOF

then this code doesn't work:

#include "Key.h"

int main() {
CKey obj;
int k;

switch (obj.key) {
case ( CKey::foo ): <---- error here
k = 4;
break;
}

return 0;
}
EOF

but when I write it all in one file then it works.
It works also when I initialze my static const class attributes like this:

class CKey
{
public:
int key;

static const int foo = 1;
};
EOF

and I think I will use this method, but must check if it works with gcc.

thanks

Share this post


Link to post
Share on other sites
Quote:
Original post by kzyczynski
It works also when I initialze my static const class attributes like this:

class CKey
{
public:
int key;

static const int foo = 1;
};
EOF

and I think I will use this method, but must check if it works with gcc.


You must have missed my last point [grin], that is only legal C++ with intergal types.

Another thing you should know there are two kinds of constants in C++ logical constant values and real constants, The above example is an example of a real constant becuase its defined in place, in the header.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement