使用const关键字在c中定义常量 [英] Defining constant in c with const keyword

查看:97
本文介绍了使用const关键字在c中定义常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能在C语言中使用 const 关键字定义常量吗?

Can you define a constant using the const keyword in C.

我发现有冲突的信息。

I am finding conflicting information.

使用#define宏并对测试值进行硬编码。在这种情况下,代码可以编译,但是当我使用const关键字时会抛出错误。

Used the #define macro and hard code the value to test. The code will compile in those cases but is throwing an error when I use the const keyword.

int main(void){

  const int  TESTARRAYSIZE = 7;
  float user_array[TESTARRAYSIZE] = {5.1, 7.2, 5.1, 8.45, 23.0,
                                       67.123, 5.1};
  float number_in_question = 5.1;

  float frequency;

  frequency = user_array[1];

  printf("%.2f", frequency);

  return(0);
}

编译错误:
< filename> ;:22:3:错误:可变大小的对象可能未初始化

,但是该错误似乎很大程度上是由于常量不是

but this error largely seems to be coming because the constant isn't setting the value.

推荐答案

使用 const 类型限定符不会不能使一个常数。 C中的常量有其自己的定义。

Using the const type qualifier doesn't make something a constant. A constant in C has its own definition.

有关 const 关键字:


如果试图通过使用带有以下内容的左值来修改用const限定类型定义的对象非const限定类型,其行为是不确定的。如果尝试通过使用具有非挥发性限定类型的左值来引用以挥发性限定类型定义的对象,则该行为是不确定的。

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

您需要的是一个常量表达式;有关详细信息,请参见C11的6.6节。

What you need there is a constant expression; see § 6.6 of C11 for details.

如果您真正想知道的不是 WTF支持 const 资格赛?但是,对于您的代码而言,正确的解决方案是什么,答案很可能只是不指定数组的大小:

If what you're really wondering isn't "WTF is up with the const qualifier?" but rather what the right solution for your code is, the answer is likely to simply not specify the size of the array:

float user_array[] = {5.1, 7.2, 5.1, 8.45, 23.0, 67.123, 5.1};

这通常被认为是好的做法,因为它实际上使您的代码更健壮。

This is generally considered good practice as it actually makes your code a bit more robust.

这篇关于使用const关键字在c中定义常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆