1

I am trying to learn 'call by reference'. I want to call a function fcn1 from the main loop and pass a reference of the local variable var to the function fcn1. Next step is to call a second function fcn2 from the function fcn1 and pass again the reference of the local loop variable var. I always get this error massage:

invalid conversion from 'int' to 'int*' [-fpermissive]

Here a small example code:

void fcn1(int *variable)
{
  fcn2(&variable);
}

void fcn2(int *variable)
{
  //do something with the variable
}

void setup()
{

}

void loop()
{
  int var = 1000;
  fcn1(&var);
}

I tried to solve that issue by using:

void fcn1(int *variable)
{
  fcn2(*variable);
}

But it's the same error.

By deleting the * respectively & it works fine, but is it still a reference?

2
  • Thanks a lot! If I interpret your answer and the link correctly, the following code works only with references, right? void fcn1(int &variable) { variable++; fcn2(variable); } void fcn2(int &variable) { Serial.println(variable); } void setup() { Serial.begin(9600); } void loop() { static int var = 1000; fcn1(var); delay(1000); } Many thanks! – piiq Jan 31 '18 at 20:47
  • Yes, however, it will not compile that way .. int & variable denotes a pointer, to increase it, you should use variable++. – Michel Keijzers Jan 31 '18 at 20:50
7
void fcn1(int *variable)
{
  fcn2(*variable);
}

This function takes a pointer to an integer as parameter, and then passes the value of the integer to the second function.

To do it by reference, use an ampersand (&, not to be confused with the address-of operator).

void fcn1(int &variable) {
  // Do something to variable
}

For example:

void increment(int &variable) { // Reference to an integer
  variable++;
}
void setup() {
  Serial.begin(115200);
  int a = 1;
  Serial.println(a); // 1
  increment(a);
  Serial.println(a); // 2
}
void loop() {}

You could achieve the same thing using pointers, but using references is much cleaner and easier to read.

void increment(int *variable) { // Pointer to an integer
  ++*variable; // dereference first, then increment value 
}
void setup() {
  Serial.begin(115200);
  int a = 1;
  Serial.println(a); // 1
  increment(&a); // address of a
  Serial.println(a); // 2
}
void loop() {}

Please note: this question is not specific to Arduino, it is just C++. For questions like this, it is best to google for 'C++ pass by reference' instead of 'Arduino pass by reference'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.