/* =============================================================================
 * 01_ints_are_not_integers.c  --  Reality #1a: fixed-width integers are a RING,
 *                                  not the mathematical integers.
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - When does x*x come out NEGATIVE? (It can.)
 *   - Is (x + y) + z always equal to x + (y + z) for ints?  (Yes -- integers are
 *     associative, even though they overflow. This is the surprise that goes the
 *     OTHER way from floats, see demo 02.)
 *   - What actually happens on overflow, and why is it 100% predictable?
 *
 * [How to build & run]
 *   make                      # builds every demo
 *   ./01_ints_are_not_integers
 *   # or directly:
 *   cc -O2 -o 01 01_ints_are_not_integers.c && ./01
 *
 * [How to read the output]
 *   Each PART prints a claim, the computed values, and whether the "usual math"
 *   property held. The closing "Observations" block states the lesson.
 *
 * [Systems link / CS:APP 2.2-2.3]
 *   A C `int` is (almost always) 32 bits of two's-complement. That means it can
 *   represent exactly the 2^32 integers from -2^31 to 2^31 - 1, arranged on a
 *   wrap-around "number circle". Arithmetic is done modulo 2^32: when a result
 *   would fall off the top, it reappears at the bottom. Mathematicians call a
 *   structure with well-behaved +, -, x that may wrap a "ring"; integers in C
 *   satisfy the ring laws (commutative, associative, distributive) exactly --
 *   the wrap is deterministic, not random.
 *
 *   ONE IMPORTANT CAVEAT: the C *standard* says SIGNED overflow is "undefined
 *   behavior" (the compiler may assume it never happens). The two's-complement
 *   wrap we show is what the hardware does and what you get with the common
 *   flag -fwrapv; without it the optimizer may do something else entirely (we
 *   demonstrate exactly that trap in demo 05). To observe the hardware wrap
 *   reliably we compute through `volatile` values and build with -fwrapv.
 * -------------------------------------------------------------------------- */

#include <stdio.h>      /* printf                                              */
#include <limits.h>     /* INT_MAX, INT_MIN -- the biggest/smallest int        */
#include <inttypes.h>   /* nothing needed here, kept for parallels with others */

/* ---------------------------------------------------------------------------
 * square_via_volatile  --  compute x*x without letting the optimizer "cheat".
 *
 * [Idea]
 *   If we wrote `return x*x;` the compiler, knowing x at compile time, could
 *   fold it to a constant OR reason that "a square is never negative" and
 *   mislead the demo. Reading x from a `volatile` local forces the compiler to
 *   actually perform the multiply at run time, so we observe the real hardware
 *   result.
 * [Parameters] x -- the value to square (as a plain int).
 * [Returns] the 32-bit int product x*x (possibly wrapped/negative).
 * [Edge cases] for |x| large enough that x*x >= 2^31, the result wraps.
 * ------------------------------------------------------------------------- */
static int square_via_volatile(int x) {
    volatile int v = x;     /* [C tip] `volatile` tells the compiler "this may  */
                            /* change underneath you; always really read it".   */
    return v * v;           /* genuine 32-bit multiply, wraps on overflow       */
}

int main(void) {
    printf("=== Demo 01: ints are not integers (a ring, not the integers) ===\n");
    printf("On this build, an int is %zu bytes = %zu bits; range [%d, %d].\n\n",
           sizeof(int), 8 * sizeof(int), INT_MIN, INT_MAX);
    /* [C tip] %zu prints a size_t, the unsigned type that sizeof returns.      */

    /* ---- PART 1: is x*x >= 0 ? ------------------------------------------- */
    printf("PART 1: Is x*x >= 0 ?  (mathematically, always yes)\n");
    int xs[] = {40000, 50000, 100000, INT_MAX};
    for (int i = 0; i < (int)(sizeof(xs) / sizeof(xs[0])); i++) {
        int x = xs[i];
        int sq = square_via_volatile(x);
        printf("  %11d * %-11d = %-12d  %s\n",
               x, x, sq, sq >= 0 ? "(>= 0)" : "(!!! NEGATIVE !!!)");
    }
    printf("  Lesson: 40000^2 fits, but 50000^2 = 2.5e9 > INT_MAX (2.1e9),\n");
    printf("          so it wraps around the number circle into a negative.\n\n");

    /* ---- PART 2: integer associativity ----------------------------------- */
    printf("PART 2: Is (x + y) + z == x + (y + z) for ints?  (yes -- a ring)\n");
    int x = INT_MAX, y = 1, z = -1;   /* x+y overflows; does the law still hold? */
    volatile int a = x, b = y, c = z; /* block constant folding again           */
    int left  = (a + b) + c;          /* overflows at (a+b), then subtracts 1    */
    int right = a + (b + c);          /* (b+c)=0 first, no overflow at all       */
    printf("  x=INT_MAX, y=1, z=-1\n");
    printf("  (x+y)+z = %d\n", left);
    printf("  x+(y+z) = %d\n", right);
    printf("  equal? %s  -- overflow is deterministic, so the ring law holds.\n\n",
           left == right ? "YES" : "NO");

    /* ---- PART 3: overflow is just modular arithmetic --------------------- */
    printf("PART 3: Overflow = arithmetic modulo 2^32, wrapping the number circle.\n");
    volatile int top = INT_MAX;
    printf("  INT_MAX     = %d\n", top);
    printf("  INT_MAX + 1 = %d   (wrapped to the most negative int = INT_MIN)\n",
           top + 1);
    volatile int bot = INT_MIN;
    printf("  INT_MIN     = %d\n", bot);
    printf("  INT_MIN - 1 = %d   (wrapped the other way to INT_MAX)\n\n",
           bot - 1);

    /* ---- Observations ---------------------------------------------------- */
    printf("Observations:\n");
    printf("  * A C int holds only 2^32 distinct values on a wrap-around circle;\n");
    printf("    x*x can be negative once the true product exceeds INT_MAX.\n");
    printf("  * UNLIKE floats (demo 02), integer +,* ARE associative: the wrap is\n");
    printf("    exact and deterministic, so the 'ring' laws still hold.\n");
    printf("  * Overflow is modular arithmetic: INT_MAX + 1 == INT_MIN. Predictable,\n");
    printf("    but a classic source of bugs (array sizes, loop bounds, hashing).\n");
    return 0;
}
