Here is the code:
#include <stdio.h>
int main(void)
{
const int SIZE = 5;
int grades[SIZE]= {72, 65, 54, 39, 79};
double sum = 0.0;
int i;
printf("My grades are: ");
for(i = 0; i < SIZE; i++)
{
printf("%d\t", grades[i]);
}
printf("\n\n");
printf("My grades average is: ");
for(i = 0; i < SIZE; i++)
{
sum = sum + grades[i];
}
printf("%.2f\n\n", sum/SIZE);
return 0;
}
When I try to compile this code, I get:
average.c: In function 'main':
average.c:12:5: error: variable-sized object may not be initialized
12 | int grades[SIZE]= {72, 65, 54, 39, 79};
| ^~~
average.c:12:24: warning: excess elements in array initializer
12 | int grades[SIZE]= {72, 65, 54, 39, 79};
| ^~
average.c:12:24: note: (near initialization for 'grades')
average.c:12:28: warning: excess elements in array initializer
12 | int grades[SIZE]= {72, 65, 54, 39, 79};
| ^~
average.c:12:28: note: (near initialization for 'grades')
average.c:12:32: warning: excess elements in array initializer
12 | int grades[SIZE]= {72, 65, 54, 39, 79};
| ^~
average.c:12:32: note: (near initialization for 'grades')
average.c:12:36: warning: excess elements in array initializer
12 | int grades[SIZE]= {72, 65, 54, 39, 79};
| ^~
average.c:12:36: note: (near initialization for 'grades')
average.c:12:40: warning: excess elements in array initializer
12 | int grades[SIZE]= {72, 65, 54, 39, 79};
| ^~
average.c:12:40: note: (near initialization for 'grades')
My understanding was that declaring and initializing const int SIZE = 5
would mean that SIZE
is a constant and does not have a variable size. I've seen answers to this same question and I can't understand how const int SIZE
does not make SIZE
a constant integer expression. Furthermore, a course I'm learning programming in C from used const int SIZE = 5
and the program compiled and ran correctly.
Why is const int SIZE = 5
incorrect, and what is correct?