gansteed
gansteed

Reputation: 65

c also has const values but they cannot be used as array bounds?

In book "The Practice of Programming By Brian W. Kernighan, Rob Pike", Page 21, the buttom of expert "Define numbers as constants, not macros", he says "C also has const values but they connot be used as array bounds, so the enum statement remains the method of choice in C.

but it conflict with my practice:

    #include <stdio.h>
    int main(void) 
    {
        const int bound = 5;
        int array[bound];

        return (0);
    }

it can pass through compiling.

Upvotes: 0

Views: 148

Answers (3)

Nestor Daniel Flores
Nestor Daniel Flores

Reputation: 140

You are using C99.

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

float read_and_process(int n)
{
    float vals[n];

    for (int i = 0; i < n; i++)
        vals[i] = read_val();
    return process(vals, n);
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

C also has const values but they connot be used as array bounds

Although this statement has been true for K&R C and ANSI C, C99 standard has introduced variable-length arrays, making your declaration valid (and their statement about usability of const in array declarations invalid).

With C99-compliant compiler you could use any expression of integral type, not even a const one, to declare the size of an array:

int n;
scanf("%d", &n);
if (n <= 0) {
    printf("Invalid array size.\n");
    return -1;
}
int array[n]; // <<== This is allowed in C99

Note: Your example uses an old rule of C by which variables without an explicit type declaration were considered int. A modern (as in "for the last twenty+ years") declaration of bound should look like this:

const int bound = 5;
//    ^^^

Upvotes: 4

haccks
haccks

Reputation: 106122

const variables are not actually constant. Thats the reason that before C99 you are not allowed to do

const int bound = 5;
int array[bound];  

C99 introduces variable length arrays which allows the above declaration.

Upvotes: 2

Related Questions