Home > Blockchain >  C array error: expression must have a constant value
C array error: expression must have a constant value

Time:03-22

I'm trying to pass values of two variables to be the dimension of the students_grades_db array, but it doesn't work and I don't know why, as both are constant variables.

const int number_students = 4;

const int number_of_notes = 4;

float students_grades_db[number_students][number_of_notes] = {0};

It doesn't work :(

CodePudding user response:

A global array declaration must have constant expressions for index sizes. References to variables (even const variables) are not constant expressions, so can't be used.

You can instead use preprocessor macros that expand to constant literals:

#define number_of_students  4
#define number_of_notes     4

CodePudding user response:

If you declare an array outside a function at file scope, it will then get static storage duration. All variables with static storage duration must have compile-time constants as initializers and if they are arrays, the array sizes must also be compile-time constants.

This means that the size has to be something like an integer constant 123 or an expression containing only integer constants.

The const keyword, non-intuitively, does not make something a compile-time constant, it only makes something read-only. C and C are different here, you code would work in C .

Possible solutions:

  • Move students_grades_db inside a function. Then you can declare array sizes using any kind of expression, including common int variables. You probably shouldn't declare that array as "global" anyhow.
  • Or swap out your constants for #define number_students 4.
  •  Tags:  
  • c
  • Related