Learn › C Programming

Variables & Constants

Learn how to declare variables, understand data types, use constants, and manage variable scope.

Declaring Variables

A variable in C is a named memory location that stores a value of a specific type. You must declare a variable before you can use it, specifying both its type and its name. C is a statically typed language, so the compiler enforces type rules at compile time. Variable names must begin with a letter or underscore and can contain letters, digits, and underscores.

#include <stdio.h>

int main(void) {
    int age = 30;
    float height = 5.9f;
    char grade = 'A';

    printf("Age: %d\n", age);
    printf("Height: %.1f\n", height);
    printf("Grade: %c\n", grade);

    return 0;
}

Basic Data Types

C provides several fundamental data types. The int type stores whole numbers, float and double store decimal numbers with different precision levels, and char stores a single character. The size of each type can vary by platform, but int is typically 4 bytes, float is 4 bytes, double is 8 bytes, and char is always 1 byte. You can use the sizeof operator to determine the exact size on your system.

#include <stdio.h>

int main(void) {
    printf("Size of int: %zu bytes\n", sizeof(int));
    printf("Size of float: %zu bytes\n", sizeof(float));
    printf("Size of double: %zu bytes\n", sizeof(double));
    printf("Size of char: %zu bytes\n", sizeof(char));

    return 0;
}

Constants with const and #define

Constants are values that cannot be changed after they are set. The const keyword creates a read-only variable that the compiler will prevent you from modifying. The #define preprocessor directive creates a macro that performs textual substitution before compilation. Using constants makes your code more readable and less prone to accidental modification of important values.

#include <stdio.h>

#define PI 3.14159265

int main(void) {
    const int MAX_USERS = 100;
    double area = PI * 5.0 * 5.0;

    printf("Max users: %d\n", MAX_USERS);
    printf("Area of circle with radius 5: %.2f\n", area);

    return 0;
}

Variable Scope

Scope determines where a variable can be accessed in your program. Variables declared inside a function are local to that function and cannot be accessed from outside. Variables declared outside all functions are global and can be accessed from any function in the file. Block scope means a variable declared inside braces is only accessible within that block, which helps prevent naming conflicts and unintended side effects.

#include <stdio.h>

int globalCount = 0;

void increment(void) {
    globalCount++;
    int localVar = 10;
    printf("Local var: %d, Global count: %d\n", localVar, globalCount);
}

int main(void) {
    increment();
    increment();
    printf("Global count from main: %d\n", globalCount);

    return 0;
}

← Introduction to C · Operators →