Search code examples
c++arraysc++11conditional-operator

How to size a const char* array based on a condition?


How to size a const char* [] array based on a condition?

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]


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.


Solution

  • 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];