1

Having this simple C++ code:

// there MUST be the *const* keyword!
const int g_size = 8;
char g_arr[g_size] = {0};

int main(){
    // there MUST'T be the *const* keyword
    int l_size  = 8;
    char l_arr[l_size] = {0};
    ...
}

Can someone please explain me why does the global array g_arr CAN'T be initialized using non const variable (removing the modifier yields an error "array bound is not an integer constant...") but local array l_arr CAN?

DarosRT10
  • 31
  • 6
  • 4
    No, `l_arr` can't be initialized like that either. It's a gcc extension that allows it, but it's not standard. – cigien Aug 10 '20 at 15:32
  • 1
    @cigien Even if gcc allows it, i would argue that you shouldn't be doing that. – Amachi Aug 10 '20 at 15:34
  • 1
    @Amachi Absolutely, I feel that "it's not standard" implies that one shouldn't do that :) – cigien Aug 10 '20 at 15:36
  • 2
    Related: [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Aug 10 '20 at 15:37
  • @cigien ahh okay, good :) – Amachi Aug 10 '20 at 15:38
  • So gcc extension **allows** defining the local arrays with non-constant variables but **disallows** (as the standard says) defining the global arrays with non-constant variables? – DarosRT10 Aug 10 '20 at 15:41
  • See this https://stackoverflow.com/questions/14075194/variable-length-arrays-vla-in-c-and-c – cigien Aug 10 '20 at 15:47

0 Answers0