Scoping confusion

Hi Root Gurus

I made a macro which calls a small function to set histogram pointer to their correct value by passing them by reference. This works in general for me but I have a special case I don’t understand.

If I call the function from inside a for loop the passing by reference doesn’t work!

There is some code below which can reproduce the “feature” (the for loop is commented out) and if you run it you see everything you expect.

if you uncomment the for loop you get this:

Can someone explain why this is?

I thought it might not allow the change to propagate outside the for loop but even inside the for loop the passing by reference seems to not work??

It is the same for me on v4-00-04 and v5-02-00.

void test()
{
  TH1D* hist;
  SetHistNotRef(hist);
  cout<<"Pointer is "<<hist<<endl;
  IntermediateStep(hist);
  cout<<"Pointer is "<<hist<<endl;
}

void IntermediateStep(TH1D*& hist)
{
  TH1D* hist2;
 /*
  for (Int_t i= 0; i< 3; i++)
  {
    SetHistRef(hist2,i);
    cout <<"Pointer at intermediate stage is "<<hist2<<endl;
  }
  */
  SetHistRef(hist2,3);
  hist = hist2;
}

void SetHistRef(TH1D*& hist,Int_t i)
{
  hist = new TH1D(TString("hist")+i,"",10,-10,10);
  hist->FillRandom("gaus",10000);
}
void SetHistNotRef(TH1D* hist)
{
  hist = new TH1D("hist","",10,-10,10);
  hist->FillRandom("gaus",10000);
}

Hi.

Yes, you are right. I think it is an interpreter problem. It can be simply reproduced
(ROOT 5.03/01)

void Set(int *& rptr) 
{ 
   rptr = new int;
   std::cout<<"in Set "<<rptr<<std::endl;
} 

void test() 
{ 
   int *ptr = 0;
   Set(ptr);
   std::cout<<ptr<<std::endl;
   ptr = 0;
   std::cout<<"In for :\n";

   for (int i = 0; i < 5; ++i) {
      Set(ptr);
      std::cout<<ptr<<std::endl;
   }
} 

I do have a very long macro which IMHO does the same thing but seems to work.

I will attach it in its entirety if someone is interested, perhaps the reason it works will be obvious to someone. It basically has a for loop over some start and end conditions and it calls a MakeHistsList function with many hist pointers by reference which come back perfectly well defined. I have no idea how this one is different to the one above in principle.

Mark
MJNHSWHistMaker.C (69.3 KB)

Hi,

this is a known problem with Cint’s optimization. You can either compile your code (.L test.C+), or disably Cint’s optimization by issuing the command “.O 0” (dot-oh zero) before you run the macro.
Axel.

Note that Masa is working on reimplementing the execution parts of CINT. Thist new implementation will solve the problem.

Cheers,
Philippe.