I encountered some really strange c code that I have never seen before, even though I have a little bit of experience. I tryed searching for it but I had no luck. This is super strange and either im really stupid or this is some wizard magic code. My question is how can the GetHelixCenter have a bool return type but still fill the helixcenterpos[] array? The GetHelixCenter function is called from another function like:
Double_t helixcenterpos[2];
GetHelixCenter(pparam,helixcenterpos);
and later on helixcenterpos is accessed:
Double_t xpos = helixcenterpos[0];
but it is untouched in between. The GetHelixCenter function looks like:
Bool_t AliV0ReaderV1::GetHelixCenter(const AliExternalTrackParam *track,Double_t center[2]){
// Get Center of the helix track parametrization
Int_t charge=track->Charge();
Double_t b=fInputEvent->GetMagneticField();
Double_t helix[6];
track->GetHelixParameters(helix,b);
Double_t xpos = helix[5];
Double_t ypos = helix[0];
Double_t radius = TMath::Abs(1./helix[4]);
Double_t phi = helix[2];
if(phi < 0){
phi = phi 2*TMath::Pi();
}
phi -= TMath::Pi()/2.;
Double_t xpoint = radius * TMath::Cos(phi);
Double_t ypoint = radius * TMath::Sin(phi);
if(b<0){
if(charge > 0){
xpoint = - xpoint;
ypoint = - ypoint;
}
}
if(b>0){
if(charge < 0){
xpoint = - xpoint;
ypoint = - ypoint;
}
}
center[0] = xpos xpoint;
center[1] = ypos ypoint;
return 1;
}
CodePudding user response:
The helixcenterpos
array is passed as the second argument:
Bool_t AliV0ReaderV1::GetHelixCenter(const AliExternalTrackParam *track,Double_t center[2]){
Here, center
decays to a pointer to the first value of your original array. Hence
center[0] = xpos xpoint;
center[1] = ypos ypoint;
write to that array.
It should be pointed out, that the parameter would be better chosen as
Bool_t AliV0ReaderV1::GetHelixCenter(const AliExternalTrackParam *track,Double_t (¢er)[2]){
so that you are sure that GetHelixCenter
always receives the correct array.
CodePudding user response:
I'm not sure if I understand your question correctly. Are you unsure why your function is capable of modifying the external array?
That's because in C when passing arrays, you're actually passing a pointer to the start of the array, instead of passing a copy of the array, as is the case with non-array types.
So, for example:
void myFunction(int a) {
a = 3;
}
int main() {
int a = 0;
myFunction(a);
std::cout << a << std::endl;
}
would still print 0
. Because the integer is copied when calling myFunction
and that copy is modified.
But when doing:
void myFunction(int a[1]) {
a[0] = 3;
}
int main() {
int a[1];
myFunction(a);
std::cout << a[0] << std::endl;
}
would print 3
, as you're actually modifying the first element of the array pointed to by a.