Re: Why does C not accept the "const" qualifier as constant?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Oct 10, 2011, at 2:14 PM, Kevin P. Fleming wrote:

> On 10/10/2011 01:10 PM, Jochen Moeller wrote:
>> Hello members,
>> 
>> In a book I found some C++ code I changed to C but then got a compiler error which I
>> don't understand. See the demo listings below, C versus C++.
>> 
>> A const variable is not accepted for the definition of an array with constant size,
>> and results in an error "Variable length array is not allowed at file scope" although
>> the variable is defined as const.
>> 
>> I tried some CFLAGS, used __const__ instead, and searched the archives without success.
>> 
>> It seems that the "const" qualifier for the C-compiler is not really constant.
>> 
>> Can this be explained and is it possible to avoid this error with some build options
>> which I'm not aware of?
> 
> In C++, 'const int' is an actual compile-time constant. In C, it's just a non-writable variable. Not quite the same thing.
> 
> -- 
> Kevin P. Fleming
> Digium, Inc. | Director of Software Technologies
> Jabber: kfleming@xxxxxxxxxx | SIP: kpfleming@xxxxxxxxxx | Skype: kpfleming
> 445 Jan Davis Drive NW - Huntsville, AL 35806 - USA
> Check us out at www.digium.com & www.asterisk.org

Right!  Instead, the C way of doing this is to use a preprocessor definition:
#define ITEMS 8

float array[ITEMS];

You are allowed to use variable-length arrays in C99 within functions, BTW.

Amittai Aviram
PhD Student in Computer Science
Yale University
646 483 2639
amittai.aviram@xxxxxxxx
http://www.amittai.com




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux