CC · Lesson 2 of 8

Variables & Data Types

C gives you direct control over data types and sizes. With great power comes the ability to cause extremely confusing bugs.

C
#include <stdio.h>
#include <stdint.h>  // for fixed-size integer types

int main() {
    // Integer types (sizes vary by platform and compiler)
    char c = 'A';      // 1 byte, -128 to 127
    short s = 32767;   // at least 2 bytes
    int i = 2147483647;    // at least 2 bytes, usually 4
    long l = 2147483647L;  // at least 4 bytes
    long long ll = 9223372036854775807LL;  // at least 8 bytes

    // Unsigned variants (no negative numbers, double positive range)
    unsigned int ui = 4294967295U;
    unsigned char uc = 255;

    // Fixed-size types from <stdint.h> (more portable)
    int8_t  i8  = 127;
    int32_t i32 = 2147483647;
    int64_t i64 = 9223372036854775807LL;
    uint8_t u8  = 255;

    // Floating point
    float f = 3.14f;       // usually 4 bytes, ~7 digits precision
    double d = 3.14159265; // usually 8 bytes, ~15 digits precision

    // Boolean (no bool in C89; use int or include stdbool.h)
    #include <stdbool.h>
    bool flag = true;
    bool other = false;

    printf("char: %c, int: %d, double: %f\n", c, i, d);
    printf("flag: %d\n", flag);  // prints 1 for true

    return 0;
}

Variables in C must be declared before use. They are NOT initialized automatically — they contain whatever garbage was in that memory location. Always initialize your variables.

C
#include <stdio.h>

int main() {
    // Uninitialized — DANGEROUS (undefined behavior)
    int x;
    // printf("%d\n", x);  // could print anything!

    // Always initialize
    int a = 0;
    double b = 0.0;
    char name[50] = "";   // zero out the string buffer

    // Constants — can't be changed after declaration
    const int MAX = 100;
    const double PI = 3.14159265358979;

    // Preprocessor macro constants (no type, replaced before compile)
    #define BUFFER_SIZE 1024
    #define SQUARE(x) ((x) * (x))  // note extra parens — important!

    printf("MAX = %d\n", MAX);
    printf("SQUARE(5) = %d\n", SQUARE(5));

    // sizeof — get size in bytes
    printf("int: %zu bytes\n", sizeof(int));
    printf("double: %zu bytes\n", sizeof(double));
    printf("char: %zu bytes\n", sizeof(char));

    return 0;
}
⚠ Warning
Reading an uninitialized variable is undefined behavior in C — the compiler is allowed to do literally anything, including generating code that does something completely unexpected. Always initialize your variables.