linux-sysprog · intermediate · ~15 min

Env var with default

`getenv` and the convention "missing or empty means absent".

Challenge

Look up an environment variable, falling back to a default when it is missing or empty.

Task

Implement const char *getenv_default(const char *name, const char *fallback) returning the value of the environment variable name if it is set and non-empty, otherwise fallback. No main — the grader calls it.

Input

  • name: the environment variable name to look up.
  • fallback: the value to return when name is absent or set to the empty string.

Output

A pointer to the variable's value if set and non-empty, otherwise fallback.

Example

CPLAT_TEST=hello   ->   getenv_default("CPLAT_TEST", "x")   = "hello"
CPLAT_TEST=""      ->   getenv_default("CPLAT_TEST", "x")   = "x"
CPLAT_TEST unset   ->   getenv_default("CPLAT_TEST", "y")   = "y"

Edge cases

  • A variable that exists but is empty is treated as absent (return fallback).

Rules

  • Use getenv; treat both NULL and the empty string as "not set".

Input format

An environment variable name and a fallback string.

Output format

The variable's value if set and non-empty, otherwise fallback.

Constraints

Treat NULL and the empty string both as "not set".

Starter code

#include <stdlib.h>

const char *getenv_default(const char *name, const char *fallback) {
    /* TODO */
    return fallback;
}

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