Reading same values from different branches

Dear root experts,

I have one weird issue: I have several variables stored in a plain ntuple, and make a for loop to retrieve each vaiable, but it always print same values starting from a certain round. Post codes here(root version: 5.34):

[code]#include “TCanvas.h”
#include “TFile.h”
#include “TTree.h”
#include
#include “TString.h”
using namespace std;
void test(){
//Get trees and variables
TString vars[]={“pt_leadinglepton”,“pt_sum”,“pt_sublepton”,“pt_j1”,“pt_j2”,“m_ll”,“m_jj”,“MET”,“m_jj_w”,“m_l1jj”,“mindR_l1j”,“mindR_l2j”,“m_all”,“Mt”,“m_l1j”,“m_l2j”,“RMS”};

TFile *f_nonres=new TFile(“miniNtuple_tV.root”);

TTree nonres=(TTree)f_nonres->Get(“signal”);
for(Int_t index=14;index<17;index++){
Float_t nonres_var;
TString var=vars[index];
cout<<"var: "<<var<<endl;
nonres->SetBranchAddress(var,&nonres_var);

  for(Long64_t entry=0; entry<2;entry++) {
      nonres->GetEntry(entry);
      cout<<nonres_var<<endl;
  }

}//end of loop
//end of manin func
[/code]
and also print out here:
root [0]
Processing src/test.cxx…
var: m_l1j
40.8006
153.531
var: m_l2j
55.0057
91.802
var: RMS
55.0057
91.802

You see from ‘RMS’, the values retrieved are corresponding to m_l2j. But if I just fix index at 16, it will print correct values:
Processing src/test.cxx…
var: RMS
1.51757
1.49868

Do I miss something? Thanks.
PS. root file is attached.

Best regards,
Mason
miniNtuple_tV.root (1.1 MB)

Try: } nonres->ResetBranchAddresses(); }//end of loop

Hi Pepe,

Thanks, that works. But I was wondering the reason, could you explain a little bit more?

Thanks,
Mason

Hi Mason,

Because without the Reset, the branch seen in the previous iteration are still attached to the memory (which eventhough the memory is not ‘technically’ invalid is still in the same place in the stack) associated with ‘nonres_var’.

Since in addition, you use TTree::GetEntry, you read all the branches at each iteration (it would be more efficient to read only the branch of interest), the consequence is that ‘nonres_var’ is set by each of the branches seen/used so far and … the value you actually see is the one for the ‘last’ branch in the list that have been seen so far.

Cheers,
Philippe.