Passing a tree as an argument to a function

Hello,
I am a relative newcomer to ROOT, and was wondering how I would pass a Tree as an argument to a function. Here’s what I did:

I created a tree that stores path lengths of multiple events in each voxel of my imaging area, and to test an algorithm, I have to declare a function that takes as argument that data stored in the tree. How do I do that??

Also, my main concern is how to refer to branches inside the function.

Hi, Dhruv.

  1. I cannot see what you did, but I’m curious now. It shouldn’t be so complicated :slight_smile:

  2. You mean TTree::GetBranch?

Have you taken a look at the documentation?

https://root.cern.ch/root/htmldoc/guides/users-guide/ROOTUsersGuide.html
https://root.cern.ch/doc/v612/classTTree.html

Hi, thanks for the reply :slight_smile:. Yes, passing a tree isn’t complicated at all. The problem is with using GetBranch function. Once it returns a pointer to the branch, how do I extract the variable that I will be referring to later in the function.

Double_t f(TTree t3){

  t3.GetBranch("h");


return h;}

Once I get the branch, my objective is to perform some operations on the variable in the branch I have used in the main function. How do I do that??

-Dhruv

Well, GetBranch returns a pointer to the branch. You should save the pointer to that branch and then return it in your function if you want to use it outside.

You’re also passing and returning everything by value, which is probably not the best of your options…

Cheers,
Xavi

Hi Dhruv,
you might be looking for SetBranchAddress, which associates a TTree branch with a local variable:

// cannot pass a TTree by value, you can pass it either by pointer or reference
double f(TTree& t3){
  double h;
  t3.SetBranchAddress("h", &h);
  return h;
}

Also note that ROOT offers several interfaces to read data from trees and you are using the oldest and sometimes trickiest one.

Cheers,
Enrico

EDIT: note that the snippet as I wrote it is useless, you need to call Tree::GetEntry to fill h with the value of that entry

Alright, I’ll change it to by reference. Thanks :smiley:

-Dhruv

Hi Enrico,
yes I tried using SetBranchAddress , and it does work. Thanks so much. :smiley:

-Dhruv

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.