Re:
produces the output 0
without errors
That may be true. It may also generate 42, or format your storage devices while playing maniacal_laughter.mp3
on your sound device :-)
The problem lies with:
int b = twice(b);
since it's functionally the same as:
int b;
b = twice(b);
Note there the use of "functionally", it's not strictly the same since one is an initialisation and one is an assignment, but they're effectively identical for the purposes of this question.
The first line simply "creates" b
and sets it to some arbitrary(a) value, the second line uses that value to change b
.
This is not an error in C, it's simply undefined behaviour. However, a good compiler should pick this up and give you a warning, though it may need some options to do this such as with gcc -Wall
:
prog.c: In function ‘main’:
prog.c:10:13: warning: ‘b’ is used uninitialized in this function [-Wuninitialized]
10 | int b = twice(b);
| ^~~~~~~~
The reason this can happen in C but not Python is that the former allows you to create an uninitialised variable. In Python, a variable either doesn't exist at all (i.e., the name is not bound to a value) or it exists with some value.
(a) "Arbitrary", in this case, uses the mathematical definition of "undetermined, not assigned a specific value" rather than the definition making it a result of some specific whim by someone. The actual term used in the ISO standard is "indeterminate" for the language lawyers among us (of which I am usually one).
Keep in mind there's nothing requiring an implementation to have a specific value for an uninitialised variable. Though unlikely, it's perfectly plausible that the following code would generate two different numbers:
#include <stdio.h>
int main(void) {
int x;
printf("%d %d\n", x, x);
}