1

I would like to define the size of a multidimensional array as a constant. What would be the best way to do this please? In the example below, MY_CONSTANT would be equal to 2. Can this constant be determined before run time?

#define MY_CONSTANT <what goes here?>

std::string myArray[][3] = { 
{"test", "test", "test"},
{"test", "test", "test"}
};
2
  • 3
    const std::size_t array_size = 2;? BTW, prefer std::array when you have constant size array, else std::vector (or std::deque). Commented Oct 9, 2013 at 16:48
  • 1
    In C++, you should prefer const variables to #define. They can be used as compile-time constants, and also respect scope. Commented Oct 9, 2013 at 16:54

3 Answers 3

10

You might use std::extent to get the size of the array at compile time:

std::string myArray[][3] = { 
  {"test", "test", "test"},
  {"test", "test", "test"}
};

const std::size_t myArraySize = std::extent<decltype(myArray)>::value;

The preprocessor will not be able to define the value directly. Of course you could use

#define MY_CONSTANT std::extent<decltype(myArray)>::value

but I guess that's not really what you want to do.

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

1 Comment

const std::size_t MY_CONSTANT = std::extent<decltype(myArray)>();
3

In C++11, you can use a constexpr function to initialise a compile-time constant:

template <typename T, size_t N> 
constexpr size_t array_size(T(&)[N]) {return N;}

constexpr size_t MY_CONSTANT = array_size(myArray);

(or use std::extent as another answer suggests; I didn't know about that).

Historically, you would need to initialise it with a constant expression like

const size_t MY_CONSTANT = sizeof(myArray) / sizeof(myArray[0]);

Comments

1

you are using C++, better use const instead of #define.

#define is a preprocessor directive which will perform textual substitution before compilation.

const int create a read only variable. so better use something like: const size_t arraySize = 2;

"Can this constant be determined before run time?"

you would have to use dynamically allocated arrays using new or better use vector from STL

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.