Is it essential the size of a 'char' array to be const

Hi all,

My question is regarding the size of an array. As i know the size of an array must be a constant and it should be know at compile time. Off course my question is regarding char arrays, please have a look at the following code,


1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
        int i = 0;
        for (; i<10; i++)
        {
                char a[i];
        }

        char b[i];

        return 0;
}


According to my knowledge this code cannot be compiled, at least it should give a warning, but actually it dosen't. Is this because array-size-const rule is not applicable for char buffers, or some other reason. Can some one please explain the reason for this?

What compiler is this and is it C or C++?
A modern compiler will optimize the loop away (as it was never there).
Is this because array-size-const rule is not applicable for char buffers, or some other reason.

the reason is:
this code compiles just fine cos it has no efect.
as modoran said....
once optimized your code will look like this:
1
2
3
4
int main() {
    int i = 0;
    return 0;
}


no effect.
Last edited on
@modoran, codekiddy, no. You're being silly. If this is due to optimization, then I bet
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
 
int main()
{
    int i;
    std::cin >> i;
    char b[i];
    b[4] = 'x';
    std::cout << b[4];
    return 0;
}
won't work? Well, it does on gcc. Any there is no way optimization would be done before syntactic analysis..

This is something that comes from C. See http://en.wikipedia.org/wiki/Variable-length_array
It is not standard C++, if I recall correctly.
That is a compiler extension (that goes against the standard).
The -pedantic-errors flag (gcc) will produce the error:
ISO C90 forbids variable length array
ISO C++ forbids variable length array
Topic archived. No new replies allowed.