In C:
20
is a constant.
unsigned int const size_of_list
is not a constant.
Title: "Why we cannot create an array with a constant in c" does not apply to this code.
const char* list_of_words[size_of_list] = {"Some", "Array"}; // Bad
An issue here (and the error message) is why a VLA cannot be initialized. That is answered here.
With a constant, array initialization works fine.
const char* list_of_words[20] = {"Some", "Array"}; // Good
Another issue is mistaking that const
makes an object a constant. It does not.
Alternative C code
int main(){
// unsigned int const size_of_list = 20;
#define size_of_list 20u
const char* list_of_words[size_of_list] = {"Some", "Array"};
for (unsigned int writing_index = 0; writing_index < size_of_list; writing_index ++)
;
return 0;
}
If you can specify the size in the array itself, then you can get it's size with the sizeof
operator. This may be better suited for having the compiler count up the size instead manual counting. When not using C99
VLAs, sizeof
also yields a compile-time constant.
#include <stddef.h> /* size_t */
int main(void) {
const char* list_of_words[] = {"Some", "Array"};
const char list_of_char[sizeof list_of_words
/ sizeof *list_of_words] = {'S','A'};
const size_t size_of_list
= sizeof list_of_words / sizeof *list_of_words;
for (size_t writing_index = 0;
writing_index < size_of_list; writing_index ++);
return 0;
}