Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use the ternary operator "?" to fill an array list in C/C++?

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

like image 263
phollox Avatar asked Mar 16 '23 05:03

phollox


2 Answers

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
like image 55
Greg Hewgill Avatar answered Apr 06 '23 10:04

Greg Hewgill


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.

like image 23
vitaut Avatar answered Apr 06 '23 10:04

vitaut