简体   繁体   English

C99和C11中的const关键字和常量表达式

[英]const keyword and constant expressions in C99 and C11

Can we actually use const keyword in C99 and C11 to build constant expressions like this? 我们实际上可以在C99和C11中使用const关键字来构建这样的常量表达式吗? What standard says about it? 有什么标准说呢?

const int n = 5;

int main()
{
   int arr[n];
}

In C89 / C90 we can't. 在C89 / C90中,我们不能。

No. const in C never means constant but it means ready-only. 不,C中的const从不表示常量,而是表示仅准备就绪。

This is the same for C90/C99/C11. C90 / C99 / C11相同。

Note that in your example, you are using a variable length array. 请注意,在您的示例中,您使用的是可变长度数组。 VLA have been introduced in C99 and the size of a VLA does not need to be a constant expression but still n is not a constant expression. VLA已在C99中引入,并且VLA的大小不必为常数表达式,但n仍不是常数表达式。

No, const does not make a constant like it does in C++. 不, const不会像C ++中那样使常量。

On the other hand, C99 did add variable length arrays (VLAs), so for auto storage class, the size doesn't need to be a constant. 另一方面,C99确实添加了可变长度数组(VLA),因此对于auto存储类,大小不必为常数。 This allows you to do things like: 这使您可以执行以下操作:

int f(int n) { 
    int array[n];
    // ...
}

So, you can't do exactly what you're asking for, but you can do something that's close enough to equivalent for many (perhaps most) circumstances. 因此,您无法完全满足您的要求,但是您可以在许多 (也许大多数)情况下都可以做得差不多。

In C, you would likely use a macro to define the value of your constant. 在C语言中,您可能会使用宏来定义常量的值。

The following is an example of what I mean by this. 以下是我的意思的示例。

#define N 5

int main() {
    int array[N];
    // ...
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM