Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this C program compile? What is wrong with this?

Tags:

c

Why doesn't this C program compile? What is wrong with this?

I have tried it on wxDevC++ and Turbo C++ 3.0.

Main.c

#include<stdio.h>
#include<conio.h>

const int SIZE = 5;

int main(int argc, char ** argv)
{    
    char array[SIZE] = {'A', 'B', 'C', 'D', 'E'};

    printf("Array elements are,\n");
    int i=0;

    for(i=0 ; i<SIZE ; ++i)
    {
        printf("%c  ", array[i]);
    }

    getch();

    return 0;
}

Error Messages on the both of the compilers are similar.

f:\_Source-Codes\main.c In function `main':

8 f:\_Source-Codes\main.c variable-sized object may not be initialized
like image 900
user366312 Avatar asked Jul 02 '10 16:07

user366312


1 Answers

Array size in C89/90 language must be specified by an integral constant expression (in general true for C99 as well). A const int object in C is not a constant expression, which is why you can't use it to specify array size. Note: this is one prominent difference between C and C++.

In C language the term constant refers to literal constants, i.e. 5, 10.2, 0xFF, 'a' and so on (enum constants are also constants, to be precise). const int object, once again, is not a constant in C and cannot be used to build constant expressions.

If you want to pre-declare a named constant to be used as array size in C, you have to use either #define or enum. The same applies to case labels, bit-field sizes and every other context requiring a constant expression.

See this for more details.

like image 174
AnT Avatar answered Oct 05 '22 11:10

AnT