C/C++ Arena

Step 6 of 6

Constants and sizeof

Constants

Some values should never change while the program runs: the number of players on a team, the length of a round, a tax rate. Put const in front of the declaration to make the variable read-only:

const int MAX_PLAYERS = 10;
MAX_PLAYERS = 12;   // error: cannot assign to variable 'MAX_PLAYERS' with const-qualified type 'const int'

If any later line tries to change it, the program doesn't compile. That turns a silent bug into an error you see immediately. It also documents your intent: a reader knows this value is fixed. Many programmers write constant names in UPPER_CASE so they stand out.

sizeof

Every type takes up a fixed number of bytes of memory. The sizeof operator tells you how many:

#include <stdio.h>

int main(void) {
    printf("char: %zu\n", sizeof(char));
    printf("double: %zu\n", sizeof(double));
    printf("long long: %zu\n", sizeof(long long));
    return 0;
}
char: 1
double: 8
long long: 8

sizeof gives a value of a special unsigned type called size_t, and the matching printf specifier is %zu. A char is 1 byte by definition. The others depend on the machine, but on this site and on almost every modern computer an int is 4 bytes (so it can hold values up to about 2.1 billion) and a double is 8.

Knowing sizes matters once you work with memory directly, which you'll do with arrays and pointers.

Your turn: declare a constant int named ROUND_TIME equal to 115, and print:

Round time: 115
int bytes: 4

Previous: Characters with char