C Programming: Memory, Pointers and the Stack ยท C Basics

Operators: Division, Remainder, ++

Integer division, the remainder, casting to get decimals, and the difference between x++ and ++x.

operators.c

#include <stdio.h>

int main(void) {
    int a = 17, b = 5;
    int quotient = a / b;          /* integer division drops the remainder */
    int remainder = a % b;
    double exact = (double)a / b;  /* cast first to get a decimal answer */
    int x = 5;
    int post = x++;                /* uses 5, then x becomes 6 */
    int pre = ++x;                 /* x becomes 7, then uses 7 */
    int both = (a > 10) && (b > 10);
    printf("%d %d %.1f %d %d %d\n", quotient, remainder, exact, post, pre, both);
    return 0;
}

Step by step

  1. a is created on the stack with the value 17. b is created on the stack with the value 5.
  2. Both are ints, so / drops the remainder: 17 / 5 = 3.
  3. % gives the remainder: 2.
  4. Casting a to double first makes it a decimal division: 3.4.
  5. x is created on the stack with the value 5.
  6. x++ uses the old value (5) first, then adds one.
  7. ++x adds one first (x = 7), then uses 7.
  8. && is true (1) only if both sides are; b > 10 is false, so 0.
  9. It prints 3 2 3.4 5 7 0.
  10. The method returns 0.
  11. 3 2 3.4 5 7 0. In C, true and false are just 1 and 0.