Search code examples
c++variablesconstantsenvironmentgetenv

C++ assign const to environment variable or default value


For an application that uses a number of environment variables, is there some kind of a convention or "best practice" when it comes to grabbing environment variables and putting them into either a struct or a bunch of const's? Obviously, I want to fallback to a default value for each and every environment variable. Right now, using the following seems like a very messy way of doing it:

char* x;
const SOME_VARIABLE;
if (NULL == (x = getenv("SOME_VARIABLE")))
    SOME_VARIABLE = 5; // default value
else
    SOME_VARIABLE = x;

I could also write a function that wraps getenv to return a default value if an environment variable is empty, but I'm not sure if that's even the best way to do it. I could also do away with using const, but that doesn't seem like a good thing to do, either.

Any thoughts?


Solution

  • How about:

    std::string GetEnvironmentVariableOrDefault(const std::string& variable_name, 
                                                const std::string& default_value)
    {
        const char* value = getenv(variable_name.c_str());
        return value ? value : default_value;
    }
    

    Used as:

    const std::string some_variable = GetEnvironmentVariableOrDefault("SOME_VARIABLE", "5");