Course contentsShow
← C
Lesson 1071 of 1,21915. Systems ProgrammingFree lesson

Environment variables in C

Environment variables in C

What you'll learn: How to access and retrieve configuration data from the operating system's environment using the getenv function.

The Global Backpack

Imagine every process in your operating system is a hiker. When a process starts, the OS hands it a "backpack" filled with useful items: the user's name, the preferred language, the current time zone, and a list of folders where programs are stored.

In systems programming, these items are called environment variables. They are key-value pairs (like USER=alice) that exist outside your program's source code, allowing you to change a program’s behavior without recompiling it.

The getenv Function

To peek inside this backpack, C provides a simple function from the <stdlib.h> library called getenv. You provide the name of the variable you want (the key), and it returns a pointer to a string containing the value.

If the variable doesn't exist, the function returns NULL. This is a crucial safety check; trying to print a NULL result will cause your program to crash.

#include <stdio.h>
#include <stdlib.h>

int main() {
    // We look for a variable named "USER" or "USERNAME"
    char *user = getenv("USER");

    if (user != NULL) {
        printf("Hello, %s! Welcome to the system.\n", user);
    } else {
        printf("User identity unknown.\n");
    }

    // Checking the system search PATH
    char *path = getenv("PATH");
    if (path != NULL) {
        printf("Your system looks for programs in: %s\n", path);
    }

    return 0;
}

Why use them?

Environment variables are the gold standard for portability. Instead of hard-coding a folder path like C:\Users\Bob\Documents, you can ask the system for HOME. This ensures your code works on any machine, for any user. They are also widely used for sensitive data, like API keys or database passwords, keeping them out of your public source code and safely stored in the system's environment.

Key takeaway

Use getenv() to fetch external configuration data, but always check for NULL to ensure the variable actually exists.