This is what I write:
const int MAX=100;
int main (){
int notas [MAX]={0};
The compiler says the following:
[Error] variable-sized object may not be initialized
[Warning] excess elements in array initializer
When I write MAX
with #define MAX 100
, it works. But I don´t understand what's the matter with doing it this way?
Despite the const
in the declaration
const int MAX = 100;
MAX
is not a constant expression (i.e., something whose value is known at compile time). Its value isn't known until run time, so the declaration of notas
is treated as a variable-length array declaration, and a VLA declaration may not have an initializer (nor may a VLA be declared at file scope, nor may it be a member of a struct
or union
type).
With the preprocessor macro
#define MAX 100
all instances of the symbol MAX
are replaced with the literal 100
after preprocessing, so it's effectively the same as writing
int notas[100] = {0};
which is why using the preprocessor macro works.