Const in C: cannot allocate array of constant size 0

A small piece of code:

void func()
{
   const int BUF_SIZE = 5;
   char scale[BUF_SIZE];
}

This code is built perfectly under C ++, but under C I have 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!

+5
source share
2 answers

In C (all variations, I believe) a const, ironically, is not a constant expression in C. In pre-C99, the lengths of the arrays must be a constant expression.

However, C99 has the concept of "variable length arrays", so if you are compiling with a compiler compatible with C99, your code must be valid, although BUF_SIZEit is not a constant expression.

+5
source

I would do something like this:

#define BUF_SIZE 5
void func(){
    char scale[BUF_SIZE];
}

It will do what you need

+2

All Articles