I am researching an interesting behavior for two code segments, that give me unexpected behavior.
Describing The behavior
Code segment 1:
#include <iostream>
using namespace std;
int main()
{
long long n;
long long m;
// cin >> n;
cout << m;
return 0;
}
When I run this (for example in https://www.onlinegdb.com/online_c++_compiler), the value printed in the console (the value inside the variable m
) is 0. This is expected and corresponds to the fact that the long long
type has a default initialization to 0 (zero initialization).
Code segment 2:
#include <iostream>
using namespace std;
int main()
{
long long n;
long long m;
cin >> n;
cout << m;
return 0;
}
By uncommenting the line with cin and adding any value, I do not get 0, but rather a different value depending on the number I input for n
. Other characteristics of this behavior are:
- For different input values for
n
, we get different values inm
. - Each time the same value is given for
n
, we get the same value inm
. - Defining
n
orm
static results in the expected behavior, which ism
carrying the value 0. - The same behavior persists if
m
,n
areint
s
The unexpected behavior is thus that m
does not have a default initialization to 0.
Discussion
My explanation
- The uncommented line,
cin >> n
, creates a new thread for execution. - The new thread creates a new stack to which all local variables are copied.
- Since
m
is not initialized in the original stack, the value it carries is indeterminate in the new stack. It depends on the state of the current stack. But the state of the stack is dependent on the state of the original copied stack, which, in turn, is dependent on the value of the inputn
.
Issues
My explanation is congruent with characteristic 3. Nevertheless, I do not know how to check for this using a single thread. Moreover, the reason might be something more than stack-related such that even with one and only one thread, the behavior persists. What do you think?