Keep local names and constants clear
Keep a fixed rack capacity
The paint rack has ten spaces. The number of cans may change, but the rack's capacity should stay fixed while this program runs.
#include <stdio.h>
int main(void) {
const int rack_capacity = 10;
int cans = 6;
{
int open_spots = rack_capacity - cans;
printf("Open rack spots: %d\n", open_spots);
}
printf("Rack capacity: %d\n", rack_capacity);
return 0;
}
const int rack_capacity = 10; declares an integer you cannot later assign a different value to. You can still read it in a calculation. cans is an ordinary integer variable.
The extra pair of braces creates an inner block inside main. A block groups statements and declarations. A local name is available from its declaration until that block's closing brace; this region is its scope.
open_spots is declared inside the inner block, so its print call must stay there. rack_capacity is declared before that block, so code both inside and after it can use the name. Moving the first print below the inner closing brace would produce a compiler error because open_spots is no longer in scope. Scope controls where a name can be used; const controls whether its value can be reassigned. They are separate rules.
Run the unchanged example. The inner block calculates and prints four open spots; the outer block then prints the capacity of ten. Finishing an inner block does not end main.