Lecture 021

Undefined Behavior for Numbers

8-bit 16-bits 32-bits 64-bits
256 bytes 64 KB 4GB 2^{64} bytes
+-128 +-32768

C standard: compiler define size of an int (implementation-defined behavior)

int's Undefined Behaviors

  1. Safety violation in C0

    • division / modulus by 0
    • INT_MIN by -1
    • shifting more than size of int
  2. Overflow!

    • compiler might not use two's complement
    • impossible to reason about int
    • gcc: -fwrapv force use of two's complement

long: 64 bits short: 16 bits char: 8 bits (1 byte) unsigned variations: always follow modular arithmetic

size_t: size of a pointer

Summary

Summary

Casting Integers

Literal numbers have type int

Casting between signed and unsigned:

Casting from small to big:

Casting from big to small

Casting between both size and sign/unsigned

Fixed-size Integers

stdint.h

stdint.h

Decimals

Float: 32 bits Double: 64 bits Calculation rounding error depend on compiler

Error Cause by Representation

Error Cause by Representation

Union and Enum

enum season {WINTER, SPRING, SUMMER, FALL};
emun season today = FALL;
if (today == WINTER) printf("snow!\n");
switch (today) {
  case WINTER:
    printf("snow!\n");
    break;
  default:
    printf("other\n");
}

Union Type allow using the same space in different ways:

Table of Content