Home > OS >  How to conditionally init const char* arr[] with ternary operator
How to conditionally init const char* arr[] with ternary operator

Time:12-10

TLDR;

How to conditionally init a const char* [] ?

const char* arr[] = (some_condition ? {"ta", "ta"} : {"wo", "lo", "lu"});

error: expected primary-expression before ‘{’ token (...)
error: expected ‘:’ before ‘{’ token (...)
error: expected primary-expression before ‘{’ token (...)
error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive]


Details

I'm using an external api that takes a const char* argv[] as input. Based on variables stored in more sane data structures, like std::string, I construct this input variable, but I'm obviously unable to do so correctly.

To be honest, the root of the problem boils down to a single trouble argument which is optional. The following works (somewhat) ..

bool use_optional = false;
std::string optional = "blah";

const char* arr[] = {
    "arg1",
    (use_optional ? optional.c_str() : ""),
    "arg3" 
};

The problem with this solution is that I get an empty entry in arr, i.e. {"arg1", "", "arg3"}, and I would very much like to avoid this.

CodePudding user response:

As a workaround, you can create 2 different arrays, and switch between them:

const char* arr1[] = {"ta", "ta"};
const char* arr2[] = {"wo", "lo", "lu"};
auto arr = some_condition ? arr1 : arr2;

Another possibility is to use vectors:

std::vector<const char*> varr;
varr.push_back("arg1");
if (use_optional) varr.push_back(optional.c_str()),
varr.push_back("arg3");
auto arr = &varr[0];
  • Related