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

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

 



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?

Thanks 

Jochen

Platform: Xcode 4.1 or 3.2.6 with GCC 4.2 for C and C++

// ******** C++ Listing ********
#include <iostream>

const unsigned int items = 8;
float array[items]; // Works only in C++, does not compile in C. Why ??

int main (int argc, char * const argv[]) {
  printf("Hello World !\n");
  return 0;
}

// ******** C Listing ********
#include <stdio.h>
#include <stdlib.h>

const unsigned int items = 8;
float array[items]; // Error: Variable length array is not allowed at file scope.
// float array[8];  // That works, of course.

int main (int argc, char * const argv[]) {
  printf("Hello World !\n");
  return 0;
}




[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