I have a case where I have to set std::string to NULL. The code is like this:
const std::string variable = "HOME";
const std::string str = getenv(variable.c_str());
Problem is, getenv()
returns NULL if it does not find the environment variable and since we can't set std::string to NULL
value, we have to assign it an empty string.
One option is:
const std::string str = (getenv(variable.c_str()) == NULL ? "" : getenv(variable.c_str()));
Only that it calls getenv() twice.
What is the best practice to achieve this result?
getenv
call? I'm not sure I follow that. It seems like the first one by itself achieves what your first two lines of code did.