问题
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