A strange effect of COUT

Hello every body,

In the following code the function 'fun' sets 'x' to the value of 'norm' which is NOT properly initialised.
In the presence of this bug the printed value of 'x' depends on whether 'HELLO!' is printed on screen or not (by commenting line 16). Does anybody know why?

Thank you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>

using namespace std;

void fun(double &x) {
        double norm;
        norm+=1;
        x=norm;  
}

int main()
{
        int i;
        double x;
        for(i=0;i<2;i++){
                if(i==1) cout<<"Hello!"<<endl;
                fun(x);
        }
        cout<<x<<endl;
}
Last edited on
Because you are using uninitialized variable norm which is undefined behavior. That means anything can happen.

As stack memory is constantly repurposed, execution of other code will change memory, then either uninitialized variables would be placed it this memory, or UB avoidane compiler optimisations will work or something else.
Topic archived. No new replies allowed.