Jim
Jim

Reputation: 107

Defining Array Size in C++

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"}
};

Upvotes: 1

Views: 1256

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254431

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]);

Upvotes: 3

Daniel Frey
Daniel Frey

Reputation: 56863

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.

Upvotes: 10

Moha the almighty camel
Moha the almighty camel

Reputation: 4443

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

Upvotes: 1

Related Questions