0

I am a beginner in C and I am practicing use of arrays. I created a constant variable for the size of the array, but when I enter it in, I am getting an error that says the size must be constant value. In terminal is highlights int on line 3 and says variable-sized object may not be initialized. It works when I put the integer 5 in the brackets.

const int SIZE = 5; 
int grades[SIZE] = {78, 67, 92, 83, 88}; //error on this line
aBasude
  • 1
  • 1
  • 2
    `const int` is not the same as a literal constant `#define SIZE 5` needed by the array declaration. (you can also use a global `enum { SIZE = 5 };`) – David C. Rankin Sep 16 '20 at 19:50
  • `This seems to work in tutorials?` Which tutorials? – KamilCuk Sep 16 '20 at 19:52
  • I am taking a coursera course and it worked for the prof. Maybe I read it wrong but I was very confused because I couldnt see the difference between my and his code. Thank you! – aBasude Sep 16 '20 at 19:56
  • 1
    You read C++ documentation where `const int` is treated differently allowing that syntax, but not in C. – David C. Rankin Sep 16 '20 at 19:57
  • 1
    That code does work with clang, but it comes with a warning: *"warning: variable length array folded to constant array as an extension [-Wgnu-folding-constant]"*. So either the prof was compiling with a C++ compiler, or the prof was using a compiler that allows that syntax as an extension to the C language. Technically speaking, it's not valid C code. – user3386109 Sep 16 '20 at 20:05
  • Alternatively, the code presented would be perfectly fine if it appeared inside a function, and was presented to a C implementation that supported the variable-length array option. Perhaps that was the context in which the instructor presented it, though that would be misleading (and one way or another, at least one student evidently was misled). VLAs may not be used at file scope, however. – John Bollinger Sep 16 '20 at 20:10
  • @JohnBollinger If the array is at function scope, and the compiler treats it as a VLA, you'll get this diagnostic: *"error: variable-sized object may not be initialized"*. The only way the OP's code works is as an extension to the language. – user3386109 Sep 16 '20 at 20:22
  • Fair enough, @user3386109, but it's unclear how similar the code presented in the question is to the code on which the OP modeled it. The latter, unknown code could have been a valid VLA declaration (without initializer). – John Bollinger Sep 16 '20 at 20:35
  • @JohnBollinger Agreed. I've never looked at coursera, so all I have to go on is what the OP posted. – user3386109 Sep 16 '20 at 20:41

0 Answers0