Reputation: 53
A small piece of code:
void func()
{
const int BUF_SIZE = 5;
char scale[BUF_SIZE];
}
This code is built fine under C++, but under C I have an errors:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
Why?
Compiler: Microsoft Visual C++ 2008
Thanks in advance!
Upvotes: 5
Views: 4978
Reputation: 452
Better yet, use enum { BUF_SIZE = 5 };
so that the debugger knows about it.
Upvotes: 1
Reputation: 83
I would do something like this:
#define BUF_SIZE 5
void func(){
char scale[BUF_SIZE];
}
That will do what you need
Upvotes: 2
Reputation: 272772
In C (all variants, I believe), a const
is, ironically, not a constant expression in C. In pre-C99, array lengths must be a constant expression.
However, C99 has the concept of "variable length arrays", so if you're compiling with a C99-compliant compiler, your code should be valid even though BUF_SIZE
is not a constant expression.
Upvotes: 5