I have a c++ program in which constants are stored within a class. And somewhere else in the code I use one of these constants as an array size.
Here is a sample:
Constants.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
class Constants
{
public:
static const unsigned int C_BufferSize;
};
#endif
Constants.cpp
#include "Constants.h"
const unsigned int Constants::C_BufferSize(128);
main.cpp
#include "Constants.h"
int main()
{
char buffer[Constants::C_BufferSize];
return 0;
}
When I compile this code with -std=c++11 -pedantic
I got the following warning:
main.cpp:5:37: warning: ISO C++ forbids variable length array ‘buffer’ [-Wvla]
I don't really understand the error since the size is a constant, my guess is that at compile time the size is unknown.
The error can be bypassed using a heap allocated table (allocated with new), but I'm forbidden to use dynamic memory allocation. Therefore I'm looking for another solution.
Warning reason - as mentioned by @nawaz already (variable size in array at compile time - might not be supported/allowed by all compilers).
can be attempted this way instead:
Typically the above issue would arise when doing some
char*
conversion tostring
(limited by actual data size in the char-buffer). Therefore in that case, this can be used something like;Reference/s here.
The definition is required and searched for, at link-time. So yes, the size is unknown during the compilation phase.
You're write this:
And then only provide the definition in
.cpp
file:But then it makes better sense to make
Constants
a namespace instead of a class:Seems more natural to me.