c 也有 const 值,但它们不能用作数组边界?

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

在书 "The Practice of Programming By Brian W. Kernighan, Rob Pike" 的第 21 页,专家的按钮 "Define numbers as constants, not macros",他说“C 也有 const 值,但它们不能用作数组边界,因此枚举语句仍然是方法在 C 中的选择。

但是和我的做法有冲突:

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

        return (0);
    }

编译通过

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

尽管此声明适用于 K&R C 和 ANSI C,但 C99 标准引入了可变长度数组,使您的声明有效(并且他们关于 const 在数组声明中的可用性的声明无效)。

使用符合 C99 的编译器,您可以使用任何整型表达式(甚至不是 const 表达式)来声明数组的大小:

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

注意:您的示例使用了 C 的旧规则,根据该规则,没有显式类型声明的变量被视为 intbound 的现代(如 "for the last twenty+ years")声明应如下所示:

const int bound = 5;
//    ^^^

const 变量实际上不是常量。这就是为什么在 C99 之前你不能做

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

C99 引入了允许上述声明的可变长度数组。

您正在使用 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);
}