Sign in to follow this  
kzyczynski

static const not const in switch

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this