0

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 :(

1
  • 1
    they are const variables not constant variables. C does not not have constant variables (C++ has constexpr which can give named constant expressions). Commented Mar 22, 2022 at 3:41

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.