-1

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?

phuclv
  • 37,963
  • 15
  • 156
  • 475
John
  • 49
  • 1
  • 7
  • 3
    `a course I'm learning programming in C from used const int SIZE = 5` then throw that course away and use some good guides from [The Definitive C Book Guide and List](https://stackoverflow.com/q/562303/995714). The author probably built in C++ mode or used MSVC which is a C++ compiler, not a C one – phuclv Apr 26 '21 at 04:00
  • @NateEldredge It did help. Thanks, Nate. – John Apr 26 '21 at 06:58

1 Answers1

-2

Why can't you use SIZE as #define SIZE ((uint8_t)5), this is also constant initialization, It's Preprocessors so it want change in run time environment,