SyntaxStudy
Sign Up
C Constants, Scope, and Storage Classes
C Beginner 1 min read

Constants, Scope, and Storage Classes

C offers several ways to define constants. The `#define` preprocessor directive creates a macro that is textually substituted before compilation. The `const` keyword declares a variable whose value cannot be changed after initialization. For integer constants, `enum` provides named values with automatic sequential numbering. Each approach has trade-offs regarding type safety, debuggability, and scope. Scope determines where a variable is visible. Local variables declared inside a function are visible only within that function's block. Global variables declared outside any function are visible throughout the entire file (and potentially other files via `extern`). Minimizing global state leads to more maintainable, testable code. Storage classes control a variable's lifetime and linkage. The `auto` class (the default for locals) means the variable lives on the stack for the duration of the enclosing block. The `static` keyword applied to a local variable makes it persist across function calls. Applied to a global, `static` restricts its visibility to the current translation unit. The `register` hint suggests the compiler store a variable in a CPU register, though modern compilers largely ignore it.
Example
#include <stdio.h>

/* Preprocessor constant — no type, no scope */
#define PI 3.14159265358979

/* const global — typed, file scope */
const int MAX_SIZE = 256;

/* enum constants */
enum Direction { NORTH = 0, EAST, SOUTH, WEST };

/* static global — visible only in this file */
static int call_count = 0;

void increment(void)
{
    static int local_persist = 0;  /* retains value between calls */
    local_persist++;
    call_count++;
    printf("local_persist=%d  call_count=%d\n",
           local_persist, call_count);
}

int main(void)
{
    const double radius = 5.0;
    double area = PI * radius * radius;
    printf("Area = %.4f\n", area);

    enum Direction dir = EAST;
    printf("Direction value: %d\n", dir);  /* prints 1 */

    increment();
    increment();
    increment();

    return 0;
}