Is a static const member variable compile time variable?

We all know C++ programming language has a lot of gotcha, but have you ever said "Gotcha!" while you are interviewing somebody? Here is the story.

I interviewed an engineer last week. His resume said he was familiar with "C++ template meta-programming". So, my interview question was about it.

The first problem to solve was a compile time variable. The immediate answer is "enum".

struct Foo {
enum { value = 1 };
};

But, how about this?

struct Foo {
const static int value = 1;
};

 

I thought const static class member variables are not evaluated at a compile time for reasons described later. However, unfortunately, I was wrong. It’s also a legal variable evaluated at compile time.

The probe is easy. We know that "enum" is a compile time variable. So, try this. It correctly compiles.

struct Foo {
const static int value = 1;
enum {
V = value,
};
};

It means const static int is compile time variable.

 

Why did I misunderstand?

The first cause was the compiler I use. One of compilers our company uses is vc6.0, which does not support in-class definition of static member variables, and I was not familiar enough with it. In vc6.0, static const member has to be defined this way:

struct Foo {
const static int value;
};
const int Foo::value = 1;

The second cause is that out-class definition is definitely not compile time variable. For example, you can even call function to initialize the variable!

int bar(){
int result;
cin >> result;
return result;
}

struct Foo {
const static int value;
};
const int Foo::value = bar();

So, with all the knowledge, I blindly believed that static const member variable was a runtime variable. Ouch.

 

Advertisements

About Moto

Engineer who likes coding
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s