Passing by reference

Hi all

the code below produce the same result and I was wandering whether in practice one way is "better" that the other and in what circumstances....
to me the second method appears to be more convenient but I believe the first method is the one more frequently used?

void setup() {
Serial.begin(9600);

int x = 10;   
Serial.print("original: "); Serial.println(x);    
displayByPointer(&x);
displayByAddress(x);
Serial.print("after functions: "); Serial.print(x); 
}

void loop() {}

void displayByPointer (int *a){
  *a = 100;
  Serial.print("method 1: "); Serial.println(*a);
}

void displayByAddress (int &a){
  a = 1000;
  Serial.print("method 2: "); Serial.println(a);
}
1 Like

Both are correct, use the one you prefer.

1 Like

That's because many people here come from a C background where passing by reference does not exist, hence we are used to play with pointers.

using references is more C++ like.

a big difference between a reference and a pointer is that the pointer can point nowhere (a null pointer) whereas a reference is always referring to something.

So to be robust, the code with the pointer should be

void displayByPointer (int *a) {
  if (a != nullptr) {
    *a = 100;
    Serial.print("method 1: "); Serial.println(*a);
  } else {
    Serial.println("null pointer error");
  }
}

The version with the reference does not need that as the compiler will ensure it's called with a reference.

so if you plan to be able to call the version with something invalid then use a pointer (there might be a use for it) but if you always expect a valid element to work with, then using the reference makes shorter code and you let the compiler do the work once.

4 Likes

Thank you both!! very clear now!

Hum, no you would need to pass a pointer to the pointer if you wanted to modify it (the original pointer)

May be I’m missing your point

Advances the pointer to the next int. It could now be invalid. References do not have the same vulnerability.

In other words, the data being referred to (the referent) can be modified but the reference itself (the pointer) cannot be changed; it is constant.

Or just program in C as far as can be managed.

I prefer the C style, it makes it clearer at the point of calling a function because there will be an explicit pointer, or an explicit taking the address of something.

I still get tripped by C++ calls by reference, as long habit leaves me to forget that now arguments to functions can be changed, a huge step from "knowing" that all calls are call by value, and the reference thing has to be done by passing a pointer.

So of course the function can be read and the truth known, it's just that you have to. Be aware.

a7

Got it

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