Brainlag
  1. Library
  2. Concepts
  3. C

Types and sizes

Every C value has a type that fixes its size in bytes. See int, char and double, measure them with sizeof, and watch an int overflow.

C9 min

A type is a size

In C, every variable has a type, and the type decides how many bytes it takes and what those bytes mean. On this site's compiler:

| type | bytes | holds | |---|---|---| | char | 1 | a small number, used for one character | | int | 4 | whole numbers, about plus or minus 2.1 billion | | long | 4 | the same as int here (8 on most laptops) | | double | 8 | numbers with a decimal point |

sizeof tells you the size in bytes. sizeof(int) is 4 here. A char is just a number: 'A' is 65, and printf("%c", 65) prints A.

Types also change the maths. 7 / 2 is two ints, so the answer is the int 3; the .5 is thrown away. 7 / 2.0 is a double: 3.5.

Overflow

Four bytes is 32 bits, so an int has a largest value: 2147483647. Add 1 and there is no bit left for the bigger number. On this machine it wraps round to -2147483648. In C, signed overflow is undefined behaviour: the language makes no promise at all, so never rely on what it does. Pick a type big enough (long long is 8 bytes) or check before you add.

Run it: sizes and a wrap

Run it, then change one thing and run it again.

main.c to run
#include <stdio.h>

int main(void) {
    printf("char %d, int %d, long %d, double %d bytes\n",
           (int)sizeof(char), (int)sizeof(int), (int)sizeof(long), (int)sizeof(double));

    char grade = 'A';
    printf("%c is stored as %d\n", grade, grade);

    printf("7 / 2 = %d, 7 / 2.0 = %.1f\n", 7 / 2, 7 / 2.0);

    int views = 2147483647;
    views = views + 1;
    printf("one more view: %d\n", views);
    return 0;
}

The average that lost its half

Three match scores average 7.67, but this prints 7.00. Fix the calculation so it prints average 7.67.

exercise_1.c to run
#include <stdio.h>

int main(void) {
    int a = 9;
    int b = 6;
    int c = 8;
    double avg = (a + b + c) / 3;
    printf("average %.2f\n", avg);
    return 0;
}

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.