Basic char allocation

Hi all,
I just thought about this basic thing and I could not find an answer for this myself. So please put in your thoughts here about.

Why is the following syntax invalid

1
2
int i=10;
     char abc[i];


whereas the following is valid

char *abc = new char[i];

and even the following seems to be invalid

1
2
const int i=10;
    char abc[i];
The C/C++ language requires that stack-based arrays have sizes known at compile time.
In the first case, because i is not a constant, line 2 violates this rule. Note that some
compilers -- namely gcc -- do allow this as an extension to the language.

In the second case, the array is heap-based. Variable length array allocations have to
be supported by the language otherwise the language is useless.

The third case AFAIK should compile since i is constant.
The third one indeed compiles, as does the first one using gcc. (I dont have any other compiler at the moment... so couldnt test...).

But what should a beginner do to avoid differences between compilers?
A person learning using gcc will always beleive that it is not necessary to have a constant size for array declaration.
You can compile with -ansi -pedantic-errors which will give you an error because it does not comply with ISO C++.

I believe it is valid in C99 but maybe not in C++?

In C++ and pre-C99 versions of C, an array's size must be a constant integral expression so that it can be calculated at compile-time. In C99, this restriction was relaxed. An array's size must be an integral expression, not necessarily a constant one. This allows you to declare a variable-length array or an array whose size is determined at runtime. For example:
Well what I am not able to understand is why are we not able to do the following for the stack based allocation alone??

1
2
int i=10;
    char c[10];


In other words, what would be the problem that prevents the compiler designers to allow the above syntax??

About the following code

1
2
int i=10;
     char c[10];


I am sorry for wrong info,, it does compile..
There is no problem; obviously gcc got it to work.

The issue is that the compiler likes to know what the offsets are of each local variable in the current stack frame
at compile time. Variable length arrays make that impossible ... the compiler now has to generate code to compute
some of the offsets, which means it must also store the actual length of the array on the stack at a known location.

EDIT: Or, to make a long story short, it makes accessing (some) local variables a wee bit slower.
Last edited on
works for me. on gcc.
remember some compilers aren't
fully compliant.
see the documentation for your compiler.
Topic archived. No new replies allowed.