3
#ifndef QWERT_H
#define QWERT_H

const int x [] = {1, 2,};
const int z = 3;
#endif


#include <iostream>
#include "qwert.h"
class Class   
{  
    int y [x[0]];  //error:array bound is not an integer constant
    int g [z];     //no problem  
};


int main ()  
{  

    int y [x[0]];      //no problem
    Class a_class;

}

I can't figure out why this doesn't work. Other people with this problem seem to be trying to dynamically allocate arrays. Any help is much appreciated.

1
  • 1
    Unrelated, but #ifndef QWERT_H should appear only in qwert.h, and #include "qwert.h" should not appear in qwert.h. Commented Jan 14, 2011 at 9:45

3 Answers 3

4

x is const (as is z obviously), but x[0] is not a constant expression. Array declarations in a class definition must have constant size specifiers.

Consider this for a moment; how would you expect the sizeof operator to evaluate the size of your class if it contains an array of unknown size at compile time?

Sign up to request clarification or add additional context in comments.

5 Comments

x[0] is const. it's not constant expression though.
x[0] is a read-only location in this case. Try to assign a value to x[0] and you'll get a compile-time "assignment of read-only location"
Yeah i see. I didn't realize there was a potential distinction between constant expressions and mere read-only-locations/consts, or that x[0] would constitute the latter. I guess the problem is that array access takes place too late in compilation for it to be allowed as a constant expression? PS. Thanks for the help guys.
@user574733: It's an "that's just how it is" issue rather than there being any fundamental technical reason (such as you hint at with "takes place too late").
@user574733: For another example that may help, consider: "extern int const x; int a[x];". Even though x is an int const, it cannot (yet) be used in an integer constant expression.
3

The main version works because your compiler has an extension to allow for variable length arrays. Array accesses cannot be constant expressions in C++03, even if the array and the index are both constant expressions, which is the source of the error.

Comments

1

The size of an array must be a constant expression. I don't believe that constant elements in an array qualify as such.

The version in main() working is probably due to a compiler extension.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.