Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const in C: Cannot allocate an array of constant size 0

Tags:

c

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!

like image 329
EvgK Avatar asked Jun 09 '11 09:06

EvgK


1 Answers

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.

like image 129
Oliver Charlesworth Avatar answered Sep 30 '22 10:09

Oliver Charlesworth