c++syntax

C++ WCHAR: Cannot allocate an array of constant size 0


I'm trying to create a WCHAR:

LONG bufferSize = foo.bar() + 1;
WCHAR wszBaz[bufferSize];

The compiler issues an error:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'wszBaz' unknown size

What am I doing wrong?

UPDATE: I added const but it still gives the same error:

const LONG bufferSize = foo.bar() + 1;
WCHAR wszBaz[bufferSize];

Solution

  • Array sizes must be constant expression:

    const int foo = 10;
    WCHAR array1[123]; // ok - 123 is a constant expression
    WCHAR array2[foo + 10]; // ok too - the expression is constant
    WCHAR array3[bar(123)]; // not ok - it may evaluate to the same thing every time, but function calls aren't seen as constant.
    

    Note that const does not make something a const expression. A const expression is something that is constant at compile time. The compiler is smart enough to figure out that something like 5+5 is a const expression, but isn't smart enough to figure out that foo(5,5) is a const expression -- even if foo(x,y) just returns x+y.

    In the next C++ standard (C++0x), you will be able to define functions as const-expressions.