Defining constant in c with const keyword

烈酒焚心 提交于 2020-01-24 16:36:08

问题


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

I am finding conflicting information.

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);
}

compile error: <filename>:22:3: error: variable-sized object may not be initialized

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


回答1:


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

See § 6.7.3 ¶ 6 of the C11 standard for a description of the const keyword:

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.

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

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.




回答2:


The compiler throws an error because when using stack memory the variables are allocated by the compiler in the pre-compilation stage, The size of the array must be a known value to the compiler in this stage

As you said if you #define the value there would be no error due to the fact it's a known hardcoded value.



来源:https://stackoverflow.com/questions/56919057/defining-constant-in-c-with-const-keyword

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!