Return values from TTree::SetBranchAddress

Hi there,

I’ve never had a need to look at the return values from TTree::SetBranchAddress before, but I recently added a branch to my standard TTree and I want to ensure compatibility with old data (which doesn’t have this branch). I was hoping I could check for these return values, but it appears they are always 0, despite what would be expected from this.

I’m hoping I’m just doing something wrong, or that there is a more straightforward way to checking if a branch exists.

I wrote this crude test to illustrate the problem. The idea was to try to SetBranchAddress to a missing branch, and see that the returned value was -5 (kMissingBranch). Instead, the returned value was 0.

void test() {
	TFile *out_file = new TFile("test.root", "recreate");
	TTree *out_tree = new TTree("test_tree", "Test tree");
	
	Int_t i;
	out_tree->Branch("value", &i, "value/I");
	
	for( int i = 100; i > 0; i-- ) {
		out_tree->Fill();
	}
	
	out_tree->Write();
	out_file->Close();
	
	delete out_tree;
	delete out_file;
	
	TFile *file = new TFile("test.root");
	TTree *tree = (TTree*)file->Get("test_tree");
	
	Int_t value, fake_value;
	Int_t r;
	
	r = tree->SetBranchAddress("value", &value);
	printf("value: r = %d\n", r);
	
	r = tree->SetBranchAddress("fake_value", &fake_value);
	printf("fake_value: r = %d\n", r);
	
	return;
}

Output:

root [0] .x test.cxx
value: r = 0
Error in <TTree::SetBranchAddress>: unknown branch -> fake_value
fake_value: r = 0

I am running version 5.32/01 on Windows 7.

Thank you for the help!

Try one of: if(MyTree->GetListOfBranches()->FindObject("SomeBranchName")) { MyTree->SetBranchAddress("SomeBranchName", &SomeVariable); } if(MyTree->GetBranch("SomeBranchName")) { MyTree->SetBranchAddress("SomeBranchName", &SomeVabiable); }
Note: the fact that “SetBranchAddress” (almost) always returns 0 is actually a bug/problem in ROOT. It has been fixed in the ROOT “trunk” and in the “v5-34-00-patches” branch, in revision 46373, as of 2012-10-06.
Hint: In case you use a TChain, before you try to “MyChain->SetBranchAddress(…);”, you need to make sure that the tree has been loaded -> execute, for example, “MyChain->LoadTree(0);” -> otherwise the “TBranch::SetBranchAddress” will always return 5 (kNoCheck = underlying TBranch not yet available so no check was made).

BTW: you MUST NOT “delete out_tree;” after you execute “out_file->Close();” (your “out_tree” is automatically deleted when you close your “out_file”) and you should execute “tree->ResetBranchAddresses();” before you “return;” from your “test()” function. See, for example, [url]GetEntry() crash in second using

Thank you! That worked like a charm. And thank you for the tip about not deleting the TTree and calling ResetBranchAddresses().