Variables are bytes
In C, a variable is not a magic box. It is a specific number of bytes somewhere in memory, and its type tells the compiler how many bytes and how to read them.
int age = 16; // a whole number
char letter = 'A'; // one byte, often used for characters
double price = 2.5; // a floating point number
long long big = 9000000000LL; // a wider whole number
You must declare the type before you use a variable, and it never changes. No surprises at runtime, which is exactly why C is fast: the compiler knows the layout of everything in advance.
The sizeof operator tells you how many bytes something takes. It gives a value of type size_t, which you print with %zu:
printf("%zu\n", sizeof(int));
Here is the honest part: most sizes are implementation-defined. The C standard only guarantees that char is 1 byte and gives minimum ranges for the others. This runner compiles to 32-bit WebAssembly, so int, long and pointers are all 4 bytes and long long is 8. On a typical 64-bit laptop, int is still 4, but pointers are 8 bytes (and long is 8 on Linux and macOS, 4 on Windows). So sizeof(int*) prints 4 here and 8 there. Neither is wrong.
To print values, printf uses format codes: %d for int, %c for char, %f for double (%.2f for two decimals), %lld for long long. Use the wrong one and you get garbage, because printf trusts you about what bytes it was handed.
Try it yourself
Edit it. Break it. Run it again.#include <stdio.h>
int main(void) {
int age = 16;
char grade = 'B';
double height = 1.72;
printf("age %d uses %zu bytes\n", age, sizeof(age));
printf("grade %c uses %zu byte\n", grade, sizeof(grade));
printf("height %.2f uses %zu bytes\n", height, sizeof(height));
printf("a pointer here uses %zu bytes\n", sizeof(int *));
return 0;
}
Your turn
Type it yourself. That is the whole trick.1Measure the types
Use sizeof to print the size of char, int and long long, one per line, in this format:
char: 1int: 4long long: 8
#include <stdio.h>
int main(void) {
printf("char: %zu\n", sizeof(char));
return 0;
}
2A tiny profile
Declare an int called level set to 7, a char called rank set to 'S' and a double called score set to 98.5. Print: Level 7, rank S, score 98.50
#include <stdio.h>
int main(void) {
// declare level, rank and score here
printf("Level ?, rank ?, score ?\n");
return 0;
}