This is probably a dumb questions. I'm modifying a code developed by someone else. I need to particularize the value of some chars array based on a logic variable ThreeDim
. I'm trying to do this without success.
int VarNumber = ThreeDim==1 ? 3 : 2;
const char* VarList [] = ThreeDim==1 ? {"X","Y","Z"} : {"X","Y"};
But the compiler is giving me errors like
error: expected ‘;’ before ‘}’ token
error: initializer fails to determine size of ‘VarList’
VarList
needs to be a const char*
due to downstream requirements. And its size should be VarNumber
. Thanks
You might consider using the preprocessor, #define THREE_DIM
, and then use #ifdef
to select one or the other code to compile:
#define THREE_DIM
#ifdef THREE_DIM
int VarNumber = 3;
const char* VarList [] = {"X","Y","Z"};
#else
int VarNumber = 2;
const char* VarList [] = {"X","Y"};
#endif
I don't think you can do this with different sized array initializers. However, you can put a conditional expression in the initializer:
const char* VarList [] = {"X", "Y", ThreeDim == 1 ? "Z" : nullptr};
This will always give you a 3 element array with the last element either "Z" or a null pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With