Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple but specific array compiling error (C)

This is what I write:

   const int MAX=100;

   int main (){
       int notas [MAX]={0};

The compiler says the following:

[Error] variable-sized object may not be initialized
[Warning] excess elements in array initializer

When I write MAX with #define MAX 100, it works. But I don´t understand what's the matter with doing it this way?

like image 427
Gabriel9721 Avatar asked Dec 04 '25 04:12

Gabriel9721


2 Answers

In this case

 const int MAX=100;

does not create a compile time constant, so the array is treated as VLA. By definition, VLAs can not be initialised, hence the error.

On the other hand, #define MAX 100 is a pre-processor macro, and based on the textual replacement property, it results in a compile time constant value of 100, then the array is not a VLA and can be initialized as per the initialization rules.

like image 116
Sourav Ghosh Avatar answered Dec 06 '25 21:12

Sourav Ghosh


This

   const int MAX=100;
int main (){
   int notas [MAX]={0};

is a declaration of a variable length array the size of which is determined at run-time because the declaration of the variable MAX is not a compile-time constant in C. Such arrays may not be initialized in declarations.

From the C Standard (6.7.9 Initialization)

3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

So you could write for example

   const int MAX=100;
int main (){
   int notas [MAX];
   memset( notas, 0, MAX * sizeof( int ) );

Otherwise you could use a compile time constant like

   enum { MAX=100 };
int main (){
   int notas [MAX]={0};
like image 23
Vlad from Moscow Avatar answered Dec 06 '25 21:12

Vlad from Moscow