Codiqo

Learn C · lesson 5 of 60 · about 7 minutes

Numeric Types

Add a CPU temperature and a rating to your report with double and char, and measure each type's box with sizeof.

What you'll learn

  • Store decimals in a double
  • Store a character in a char
  • Check sizes with sizeof

Pick the right box

Your report only uses ints so far. C has a type for each kind of value, and the type decides how big the box in memory is and how its bytes are read:

| Type | Holds | Example |
|---|---|---|
| int | whole numbers | 43 |
| double | numbers with decimals | 47.5 |
| char | one character | 'A' |

A char is really a small number: every character has a code, so 'A' is stored as 65, and 'A' + 1 is 66, the code for 'B'.

A temperature and a rating

#include <stdio.h>

int main(void) {
    double cpu = 47.5;
    char rating = 'A';
    printf("CPU: %.1f C\n", cpu);
    printf("Rating: %c (code %d)\n", rating, rating);
    printf("One worse: %c\n", rating + 1);
    return 0;
}

Output

CPU: 47.5 C
Rating: A (code 65)
One worse: B

Types have sizes

sizeof tells you how many bytes a box takes. A bigger box can hold bigger or more precise values. Print the answer with %zu, the placeholder for sizes.

Step through it to see how big each box is

#include <stdio.h>

int main(void) {
    double cpu = 47.5;
    int files = 43;
    char rating = 'A';
    printf("Sizes: %zu, %zu and %zu bytes\n", sizeof(cpu), sizeof(files), sizeof(rating));
    return 0;
}

Output

Sizes: 8, 4 and 1 bytes

When a box is full

4 bytes can only hold so many numbers. The biggest int is 2147483647, called INT_MAX in limits.h, and the smallest is INT_MIN. Going past them is an overflow: C doesn't stop you, and the result is nonsense, often a big negative number. That's why sizes matter.

The limits of an int

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

int main(void) {
    printf("Biggest int: %d\n", INT_MAX);
    printf("Smallest int: %d\n", INT_MIN);
    return 0;
}

Output

Biggest int: 2147483647
Smallest int: -2147483648

Tip

Single quotes make one char ('A'); double quotes make text ("A"). Mixing them up is a classic C mistake.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.