Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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.

>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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading