when I wrote this code in c
#include <stdio.h>
int main(void) {
const int k = 7;
int a[k];
k = 9;
return 0;
}
there was an error saying that the k in the brackets needs to be a constant value(expression must have a constant value) and the other k needs to be a modifiable value(expression must be a modifiable lvalue). This doesn't make any sense. Am I doing something wrong? I thought that you can put constant variables as the size of an array.
CodePudding user response:
const
-qualifying a variable does not make it a compile time constant, so int a[k]
declares a variable length array. Variable lenghth arrays are only supported in C99 and later and not all compilers support them.
Also, with k = 9
, you are trying to modify a const
-qualified variable, which is not allowed.
Solution would be to either use C99 or later and a compiler that supports variable length arrays or (in this case probably better) to define the array size as a preprocessor constant (e.g. #define k 10
) .
CodePudding user response:
Am I doing something wrong? I thought that you can put constant variables as the size of an array.
Yes, in C99 and later when variable length arrays (VLA) are supported.
Earlier versions of MSVC do not support VLA nor C99.
As of 2020 Astute readers will note that VLAs are also not supported in MSVC C11.
why does it say that it needs to be modifiable and it needs to be a constant
These are 2 different problems in 2 lines of code.
When variable length arrays (VLA) are not supported, an array declaration width must be a constant. const int k
is not a constant.
const int k = 7;
int a[k]; // k is not a constant.
// Alternate
#define K 7
int a[K]; // K is a constant.
Modifying a const
object is prohibited.
const int k = 7;
...
k = 9;
Instead,
int k = 7;
...
k = 9;