Code: Blocks the Mingw compiler error: variable object cannot be initialized

I am creating a simple terminal fantasy game using C ++. I seem to have encountered the error: error: objects with a variable object size cannot be initialized. "Here is the code:

string useItem(int item) { string items[item] = {"HP Potion","Attack Potion","Defense Potion","Revive","Paralize Cure"}; } 

I want to use this function to access and return an item. How can I fix this error. I am using Code :: Blocks with the mingw compiler.

+2
source share
1 answer

There are a couple of problems here, one variable array length is a C99 function and is not part of the C ++ ISO, but several compilers support this function as an extension including gcc .

Secondly, C99 says that variable-length arrays cannot have an initializer, from the draft C99 draft section 6.7.8 Initialization:

The type of the initialized object must be an array of unknown size or the type of an object that is not an array of variable length.

and alternative is to use:

 string items[] = { ... } ; 

and an array of unknown size will have its own size, determined by the number of elements in the initializer.

Alternatively, the C ++ idiomatic way of having an array of variable sizes would use std :: vector .

+2
source

Source: https://habr.com/ru/post/913078/


All Articles