linux-sysprog · beginner · ~15 min

getenv with a default

Read the environment with a fallback.

Challenge

getenv returns NULL when a variable is unset. Wrap it so callers always get a usable value via a caller-supplied default.

Task

Implement const char *getenv_or(const char *name, const char *dflt) that returns the value of environment variable name, or dflt if name is not set.

Input

  • name: environment variable name to look up.
  • dflt: fallback string returned when name is unset.

Output

The variable's value if set, otherwise dflt.

Example

// CPLAT_TEST_VAR = "hi"
getenv_or("CPLAT_TEST_VAR", "x")    ->   "hi"
getenv_or("CPLAT_NOPE_VAR", "def")  ->   "def"

Edge cases

  • Unset variable (getenv returns NULL): return dflt.

Input format

name: variable to look up; dflt: fallback when unset.

Output format

The variable's value, or dflt if unset.

Constraints

Return dflt when getenv returns NULL.

Starter code

#include <stdlib.h>

const char *getenv_or(const char *name, const char *dflt) {
    /* TODO */
    return dflt;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.