2

I'm trying to define a stack c-style array whose size is taken from const array and is known in compile-time.

const int size[2]={100, 100};
int ar[size[0]]; //error: expression must have a constant value

It fails. How it can be fixed?

3
  • 1
    It works with g++4.4. It works also on ideone Commented Sep 24, 2013 at 14:59
  • if you know the size at compile time you can always stick that in as the array size Commented Sep 24, 2013 at 15:06
  • 1
    @cpp: That's because GCC supports C-style variable-length arrays as a non-standard extension. Commented Sep 24, 2013 at 15:20

3 Answers 3

3

"array whose size is taken from const array and is known in compile-time"

With C++11 you can have :

constexpr int size[2]={100, 100}; // size[0] is Compile-time constant

Use -std=c++11 or -std=c++0x to compile

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

1 Comment

@cpp: No it doesn't. It works with a hybrid of C++98 and C99 that supports variable-length arrays, but in standard C++ you need constexpr to use array elements as compile-time constants - and that wasn't available before 2011.
2

Some options (with varying degrees of popularity):

  1. Use constexpr (not supported in Visual Studio)
  2. Use a Vector
  3. Use dynamic allocation
  4. Use a const int (C99 or newer or C++)
  5. Use an enum
  6. Use a MACRO to define the size (since it's known at compile time)

2 Comments

1. constexpr could be a the best solution but it is not supported in Visual Studio 2010 2.3. Use a Vector/Use dynamic allocation -- this is not what I need 4. Use a MACRO / define - is not better than just using consts
Since you're using C++ you can do that, this is also possible if using a modern C compiler (C99 or newer - this will technically be a variable length array) but will not work on MSVC if you compile the code as C code.
1

C++ array sizes must be constant expressions, not just constant data. Array data, even though const, is not a constant expression.

array size and const

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.