but that still doesn't explain to me how the code still runs without error and produces 89...
The C compilers provide set of options which you can use to request or suppress warning messages. For e.g. if you are using the gcc
compiler then it provides the set of options which you can use while compiling your code. One of the gcc
option is -Wall
which enables all the warning about constructions. If you compile your program with this -Wall
then compiler report the warning about the use of uninitialized variable in your program:
# gcc -Wall prg.c
prg.c:8:7: warning: variable 'currentyr' is uninitialized when used here [-Wuninitialized]
age = currentyr - birthyr;
^~~~~~~~~
prg.c:5:14: note: initialize the variable 'currentyr' to silence this warning
int currentyr;
^
= 0
prg.c:8:19: warning: variable 'birthyr' is uninitialized when used here [-Wuninitialized]
age = currentyr - birthyr;
^~~~~~~
prg.c:6:12: note: initialize the variable 'birthyr' to silence this warning
int birthyr;
^
= 0
2 warnings generated.
See the warning messages related to variables uninitialized when used.
Also, you can convert these warning messages to error by using -Werror
option of gcc
compiler.
From C Standards#6.7.9p10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
On your system the calculation using those indeterminate values is producing result 89
. You may not get result 89
every time when you run your program. On my system, I am getting -
I am 218173908 years old