Strange behavior in C++

I have the following program:

int main(int argc, char** argv){
      unsigned long int mean=0;
      
      for(int i=1;i<10;i++){
           mean+=poisson(12);
           cout<<mean<<endl;
       }
       cout<<"Sum of poisson: "<< mean;
       return 0;
}

when I run it, I get the output:

15
26
41
56
73
82
92
106
116
Sum of poisson: 116

However, if I comment the line " cout<<mean<<endl; ", I get the following unexpected output

Sum of poisson: 22

What is going on? Why the "cout" line is affecting the variable mean?
I'm using linux, with the following commands

Compile: g++ -Wall -c "%f"
Build: g++ -Wall -o "%e" "%f"

gcc version: 4.4.1

Below is the complete code with the poisson function.

untitle.cpp

#include <iostream>

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;


#define RAND_UNIFORM (double)rand()/(double)RAND_MAX

 unsigned long int poisson(double lambda){
	double g,p=exp(-lambda);
	double u=RAND_UNIFORM;
	unsigned long int k=0;
	while (u>g){
		p*=(lambda/(double)(++k));
		g+=p;
    };
	return k;
};

int main(int argc, char** argv){
      unsigned long int mean=0;
      
      for(int i=1;i<10;i++){
           mean=mean+poisson(12);
           cout<<mean<<endl;
       }
       cout<<"Sum of poisson: "<< mean;
       return 0;
}

Any help would be much appreciated.
santiagorf

The variable g in function poisson is not initialized so the behavior is undefined.

1 Like

Thank you!
That solved the problem!!
I's been five years since I haven't programmed in C. I'll have to review the syntax since I though I was initializing both g and p.
I still wonder why if I uncomment the cout line the program works fine.

To find out the reason, you can dig into the assembly code that g++ produced. But I guess by calling cout, g++ pushed small values onto the stack so that the uninitialized variable g doesn't have a huge value which is what happened with calling cout. With a huge value of g, the while loop is never entered, so the function returns 0 most of the time.

Thank you so much for the information.

1 Like