← Exercises|

How big is an int?

Predict3 of 14 · about 6 min

How big is an int?

C does not promise a size for int. It promises a minimum range, and lets each machine choose. sizeof is how you ask this machine what it actually chose; <limits.h> is how you ask for the smallest and largest value a type can hold.

This practice runtime is a 32-bit machine: char is 1 byte, short 2, int 4, long 4, double 8. The laptop you build the project on is probably 64-bit, where long is usually 8. That difference is exactly why code that assumes a size breaks when it moves.

sizeof produces a size_t, an unsigned type. Printing it with %d is a mismatch — cast it to int, or use %zu.

Example

#include <stdio.h>
#include <limits.h>

int main(void) {
    printf("int is %d bytes, from %d to %d\n", (int)sizeof(int), INT_MIN, INT_MAX);
    return 0;
}

prints: "int is 4 bytes, from -2147483648 to 2147483647\n"

Before you run it

printf("%d\n", (int)sizeof(char) + (int)sizeof(short) + (int)sizeof(int));

On this 32-bit practice machine, what does that print?

Your task

Print one line per type in this exact form, using sizeof for the sizes: char=1 short=2 int=4 long=4 double=8 — but work every number out with sizeof rather than typing it.

  • ·Work the sizes out with sizeof rather than typing the numbers

Stuck?

Explain it

Your project will run this on a 64-bit Linux machine. Which number will probably differ, and why does that matter?

Not graded — this is for you.

Where this goes

Project 2 is this investigation done properly: sizes, ranges, and what happens at the edges. You have just written its first few lines.