linux-sysprog · beginner · ~15 min

Boolean environment flag

Interpret an env var as a boolean.

Challenge

Feature flags are often passed through the environment as strings. Interpret one as a boolean.

Task

Implement int env_is_true(const char *name) that returns 1 if environment variable name is set to exactly "1" or "true", else 0.

Input

  • name: environment variable to read.

Output

1 if the value is exactly "1" or "true"; 0 otherwise (including when unset).

Example

// CPLAT_FLAG_A=1, CPLAT_FLAG_B=true, CPLAT_FLAG_C=no
env_is_true("CPLAT_FLAG_A")   ->   1
env_is_true("CPLAT_FLAG_B")   ->   1
env_is_true("CPLAT_FLAG_C")   ->   0
env_is_true("CPLAT_FLAG_Z")   ->   0   (unset)

Edge cases

  • Unset variable: return 0.
  • Any other value (e.g. "no", "yes", "0"): return 0.

Input format

name: environment variable to read.

Output format

1 if value is exactly "1" or "true", else 0.

Constraints

Unset or any other value counts as false.

Starter code

#include <stdlib.h>
#include <string.h>

int env_is_true(const char *name) {
    /* TODO */
    return 0;
}

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