Search code examples
cconstantsdeclarationliteralsvariable-length-array

Why can we not use an const int to initialize the size of a char array?


The following code snippet is illegal in C, but works perfectly in C++.

Why can we not use a const to help initialize the length of an array in C?

#include <stdio.h>
#include <string.h>

int main () {

   const int size = 6;
   char name[size] = "hello";
   printf("%s", name);

   return 0;
}

Solution

  • In C, an array whose size is not an integer constant expression is a variable length array, and such arrays cannot be initialized because their size is not know at compile time.

    A variable with the const qualifier does not count as an integer constant expression in C, so that makes name a variable length array resulting in the error when you attempt to initialize it.

    C++ on the other hand has different rules for constants. A const qualified variable whose initializer is an integer constant expression is considered a compile time constant in C++ and therefore an array using such a variable to specify its size may be initialized.