Passing a variable to a function by reference

I've researched for an hour and saw what I thought would be answers, but can't figure out why this simple example does not work. Programmed for over 30 years, but not in C++.

// Pins

int pinA_InEyelids = A0;

// Variables

long currInEyelids = 0; // 0 = eyes closed
long prevInEyelids = 0;

// Functions

  long differenceA(int port, long curr, long prev) // Analog Port. Curr & Prev both passed by reference
{  
    curr = analogRead(port);
    long diff = prev - curr;
    prev = curr;
    return diff;
}

// Start Up

void setup() {

}

// Continues Loop

void loop() {

    if (differenceA(pinA_InEyelids, &currInEyelids, &prevInEyelids) > 0) { // If Move-Eyelid is active
    
    }
  }

Here's my errors:

sketch_Dragon_V01.ino: In function 'void loop()':
sketch_Dragon_V01:30: error: invalid conversion from 'long int*' to 'long int'
sketch_Dragon_V01:30: error: initializing argument 2 of 'long int differenceA(int, long int, long int)'
sketch_Dragon_V01:30: error: invalid conversion from 'long int*' to 'long int'
sketch_Dragon_V01:30: error: initializing argument 3 of 'long int differenceA(int, long int, long int)'

long differenceA(int port, long curr, long & prev) // Analog Port. Curr & Prev both passed by reference

...

if (differenceA(pinA_InEyelids, currInEyelids, prevInEyelids) > 0) { // If Move-Eyelid is active

The function definition must declare the variable as being passed by reference. What you're doing is passing an address (i.e. - a pointer) to a function expecting a long.

// Pins

int pinA_InEyelids = A0;

// Variables

long currInEyelids = 0; // 0 = eyes closed
long prevInEyelids = 0;

// Functions

  long differenceA(int port, long& curr, long& prev) // Analog Port. Curr & Prev both passed by reference
{  
    curr = analogRead(port);
    long diff = prev - curr;
    prev = curr;
    return diff;
}

// Start Up

void setup() {

}

// Continues Loop

void loop() {

    if (differenceA(pinA_InEyelids, currInEyelids, prevInEyelids) > 0) { // If Move-Eyelid is active
    
    }
  }

Regards,
Ray L.

1 Like

Thanks. Googled a C++ reference and saw that. Sorry to waste your time.

Much appreciated.