Limits: overflow and precision
Every type has limits. See what happens at them.
The largest int
At the top add #include <limits.h>: it declares the limits of the types. At the end of the program, before return 0;:
printf("\n");
printf("Largest int: %d\n", INT_MAX);
INT_MAX is 2,147,483,647: over two billion, but not endless.
Overflow
How many seconds are there in a hundred years? Try:
int century = 100 * 365 * 24 * 60 * 60;
The program doesn't build:
C:/.../practice/02/main.c:28:39: error: integer overflow in expression of type 'int' results in '-1141367296' [-Werror=overflow]
3,153,600,000 doesn't fit in an int, so the result "wrapped around" to a negative number. That is overflow. Change the type to long long:
long long century = 100 * 365 * 24 * 60 * 60;
The error is still the same! The right-hand side is worked out before it is stored in the variable, and all its numbers are int, so the product is worked out as an int too. The first number has to be a long long: the suffix LL.
long long century = 100LL * 365 * 24 * 60 * 60;
printf("100 years: %lld s\n", century);
This time the compiler caught the overflow, because all the numbers are known in advance. When the numbers come from input, it can't see them: on Windows the program quietly prints a wrong result, and on GitHub UBSan stops it with the message runtime error: signed integer overflow.
0.1 + 0.2
The last line:
printf("0.1 + 0.2 = %.17f\n", 0.1 + 0.2);
A double stores numbers in binary, and in binary 0.1 is an endless fraction, like 1/3 in decimal. So only a very close value is stored, and with 17 digits you can see it. With %.2f it shows 0.30, so day to day you don't notice. But never compare two double values with == (topic 3), and count money in cents, as whole numbers.
Run it
Type 2007, 9, 8, 8. The card gains:
Largest int: 2147483647
100 years: 3153600000 s
0.1 + 0.2 = 0.30000000000000004
Commit: Show overflow and precision.