# pass variable by reference \[pointer\] or by value

**URL:** <https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339>\
**Category:** Programming\
**Created:** [December 1, 2016, 9:20pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339 "2016-12-01T21:20:40Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![droopy4u](https://avatars.discourse-cdn.com/v4/letter/d/8797f3/32.png) [@droopy4u](https://forum.arduino.cc/u/droopy4u)\
**Post date:** [December 1, 2016, 9:20pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/1 "2016-12-01T21:20:40Z")

</div>

On arduino I have some problems, I don't really understand.

- A simple example of just one variable referencing to another variable.

In C

```cpp
 int *p; // reference
  int a;
  p = &a;
  // print  p -  address
  // print &p -  address of memory location 'p'
  // print *p -  dereferencing : returns value on that address
  // 'a' MUST BE initialized and then 'p' allocated to 'a' ####
  a = 10;
  p = &a;
  
  print  p -  address
  print &p -  address of memory location 'p'
  print *p -  dereferencing : returns value on that address

```

On the arduino

```cpp
  int a = 1;
   int *b = &a;
   *b += 1;
   
  //now a == 2 (and b's value is a pointer to the location of a in memory)
  Serial.print("a -  ");
  Serial.println(a, DEC );
  Serial.print("b -  ");
  Serial.print(*b, DEC );  // dereferencing

```

So I have the ERROR _**error: call of overloaded 'println(int\*&, int)' is ambiguous**_ if I try

```cpp
Serial.print(b, DEC );   // address of 'b'
// OR
Serial.print(&b, DEC );  // address of memory location 'p'

```

- My original intension is to make a swap function using reference

```cpp
/*
Variables
*/
const long SERIAL_SPEED=38400;//baud rate of the serial communication

struct rect {
  int width;
  int height;
};

void swap(struct rect *input);

void swap(struct rect *input) {
    int tmp = input->width;
    input->width = input->height;
    input->height = tmp;
}

void setup() {

    Serial.begin(SERIAL_SPEED);      // open the serial port at SERIAL_SPEED bps:

    struct rect first;
    first.width = 111;
    first.height = 222;  

    Serial.println( "\n -- BEFORE -- ");
    Serial.print( "  - first.width : ");  Serial.println(first.width,  DEC);
    Serial.print( "  - first.height : ");  Serial.println(first.height,  DEC);

    swap($first);
    
    Serial.println( "\n -- AFTER -- ");
    Serial.print( "  - first.width : ");  Serial.println(first.width,  DEC);
    Serial.print( "  - first.height : ");  Serial.println(first.height,  DEC);

```

Thks

---

<div class="post-metadata">

**Author:** ![lloyddean](https://avatars.discourse-cdn.com/v4/letter/l/439d5e/32.png) [@lloyddean](https://forum.arduino.cc/u/lloyddean)\
**Post date:** [December 1, 2016, 10:07pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/2 "2016-12-01T22:07:07Z")

</div>

```cpp
swap($first);

```

What are the chances you meant -

```cpp
swap(&first);

```

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [December 1, 2016, 10:34pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/3 "2016-12-01T22:34:37Z")

</div>

```cpp
 int *p; // reference

```

No, it is NOT. It is a pointer that does not (yet) point to anything.

---

<div class="post-metadata">

**Author:** ![arduino\_314](https://avatars.discourse-cdn.com/v4/letter/a/d2c977/32.png) [@arduino\_314](https://forum.arduino.cc/u/arduino_314)\
**Post date:** [December 1, 2016, 10:59pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/4 "2016-12-01T22:59:43Z")

</div>

> droopy4u:  
> My original intension is to make a swap function using reference[/li][/list]

First of all, notice this is C++, not C.

In C++ you can pass the parameter by:

1. Value
2. Reference
3. Pointer

Your intention is to do it by pointer, not by reference and you do it right, except you call it wrong (as corrected by others).

To send it by reference, you should:

```arduino
void swap_reference(struct rect &input) {
  int tmp = input.width;
  input.width = input.height;
  input.height = tmp;
}
...
swap_reference(first);

```

---

<div class="post-metadata">

**Author:** ![KeithRB](https://avatars.discourse-cdn.com/v4/letter/k/74df32/32.png) [@KeithRB](https://forum.arduino.cc/u/KeithRB)\
**Post date:** [December 1, 2016, 11:09pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/5 "2016-12-01T23:09:56Z")

</div>

```cpp
void swapInt( int*a, int *b)
{
    int c = *a;
    *a = *b;
    *b = c;
}

// usage
swapInt(&int1, &int2);

```

You can probably use a Template to make it type agnostic, but I am a C guy.

---

<div class="post-metadata">

**Author:** ![lloyddean](https://avatars.discourse-cdn.com/v4/letter/l/439d5e/32.png) [@lloyddean](https://forum.arduino.cc/u/lloyddean)\
**Post date:** [December 2, 2016, 12:23am UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/6 "2016-12-02T00:23:02Z")

</div>

The term 'reference' in this usage has multiple meanings depending on the context.

Some C tutorials do indeed refer to passing by address as passing by reference, although from a C++ programmers perspective this not quite right.

[https://www.tutorialspoint.com/cprogramming/c\_function\_call\_by\_reference.htm](https://www.tutorialspoint.com/cprogramming/c_function_call_by_reference.htm)

---

<div class="post-metadata">

**Author:** ![PaulMurrayCbr](https://avatars.discourse-cdn.com/v4/letter/p/74df32/32.png) [@PaulMurrayCbr](https://forum.arduino.cc/u/PaulMurrayCbr)\
**Post date:** [December 2, 2016, 3:02am UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/7 "2016-12-02T03:02:42Z")

</div>

> error: call of overloaded 'println(int\*&, int)' is ambiguous

Well, evidently Serial.println doesn't take those arguments. It won't print out a pointer to int - not on the arduino at least. Try casting the pointer to an int.

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1105255_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [December 2, 2016, 3:43am UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/8 "2016-12-02T03:43:30Z")

</div>

Paul M has the right solution:

```cpp
void setup() {
  // put your setup code here, to run once:
  int a = 1;
  int *b = &a;
  *b += 1;

  Serial.begin(115200);

  //now a == 2 (and b's value is a pointer to the location of a in memory)
  Serial.print("a -  ");
  Serial.println(a, DEC );
  Serial.print("b -  ");
  Serial.println(*b, DEC );  // dereferencing

  Serial.println( (int) b, DEC );  // NO! This is the content of the pointer variable b
  // OR
  Serial.println( (int) &b, DEC );  // address of memory location where b is stored
  Serial.println( (int) &a, DEC );  // address of memory location where a is stored
}

void loop() {
  // put your main code here, to run repeatedly:

}

```

I ran this code on a Mega 2560 Pro Mini the output is:

a - 2  
b - 2  
8697  
8695  
8697

Keep in mind that the content of _b_ (i.e., its rvalue), since it is a properly-initialized pointer, should be the memory address of variable _a_. Any pointer variable should only hold one of two values: 1) NULL, in which case it points to no valid data, or 2) a memory address. This says the rvalue of _b_ is 8697 and that variable _b_ "lives" at memory address 8695 (i.e., the lvalue of _b_). The third number is where variable _a_ lives in memory (i.e., the lvalue of _a_). The numbers tell you that the rvalue of _b_ is the lvalue of _a_. That is, _b_ points to where _a_ lives in memory. Since _b_ knows where variable _a_ lives in memory, _b_ can change its value "indirectly" using the process of indirection.

Read that paragraph about 50 times and it will make sense.

---

<div class="post-metadata">

**Author:** ![droopy4u](https://avatars.discourse-cdn.com/v4/letter/d/8797f3/32.png) [@droopy4u](https://forum.arduino.cc/u/droopy4u)\
**Post date:** [December 2, 2016, 4:16pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/9 "2016-12-02T16:16:23Z")

</div>

> KeithRB:
> 
> ```arduino
> void swapInt( int*a, int *b)
> 
> ```

{  
&nbsp; &nbsp; int c = \*a;  
&nbsp; &nbsp; \*a = \*b;  
&nbsp; &nbsp; \*b = c;  
}

// usage  
swapInt(&int1, &int2);

> ```arduino
> 
> You can probably use a Template to make it type agnostic, but I am a C guy.
> 
> ```

Could you please explain how to do about the template, thx

---

<div class="post-metadata">

**Author:** ![lloyddean](https://avatars.discourse-cdn.com/v4/letter/l/439d5e/32.png) [@lloyddean](https://forum.arduino.cc/u/lloyddean)\
**Post date:** [December 2, 2016, 7:40pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/10 "2016-12-02T19:40:02Z")

</div>

Header file ...

```cpp
// File - swap.h

#ifndef swap_H
#define swap_H

template<typename T>
void swap(T& lhs, T& rhs)
{
    T  t  = lhs;
    lhs    = rhs;
    rhs    = t;
}

#endif

```

... example usage file ...

```cpp
// File - swap.ino

#include "swap.h"

struct rectT
{
    int width;
    int height;
};

void loop()
{  }

void setup()
{
    struct rectT  rect = { 100, 200 };
    
    swap(rect.width, rect.height);
}

```

---

<div class="post-metadata">

**Author:** ![gfvalvo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gfvalvo/32/1013044_2.png) [@gfvalvo](https://forum.arduino.cc/u/gfvalvo)\
**Post date:** [December 2, 2016, 8:19pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/11 "2016-12-02T20:19:36Z")

</div>

> arduino\_314:  
> In C++ you can pass the parameter by:
> 
> 1. Value
> 2. Reference
> 3. Pointer

That’s interesting. Having not yet jumped into learning C++, I did not know that. The way I keep it straight in my head for plain old C is that parameters are ALWAYS passed to functions by VALUE. That value may be the value of a pointer variable, so it’s a reference to another variable. But, it’s the VALUE of whatever was inside the (..) of the calling statement.

So code like:

```arduino
void myFunct(int);

void setup() {
  int myVariable;

  myFunct(myVariable);

}

void myFunct(int dog) {
  dog++;
}

```

Will never change the value of myVariable

---

<div class="post-metadata">

**Author:** ![droopy4u](https://avatars.discourse-cdn.com/v4/letter/d/8797f3/32.png) [@droopy4u](https://forum.arduino.cc/u/droopy4u)\
**Post date:** [December 2, 2016, 9:32pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/12 "2016-12-02T21:32:37Z")

</div>

> econjack:  
> Keep in mind that the content of _b_ (i.e., its rvalue), since it is a properly-initialized pointer, should be the memory address of variable _a_. Any pointer variable should only hold one of two values: 1) NULL, in which case it points to no valid data, or 2) a memory address. This says the rvalue of _b_ is 8697 and that variable _b_ "lives" at memory address 8695 (i.e., the lvalue of _b_). The third number is where variable _a_ lives in memory (i.e., the lvalue of _a_). The numbers tell you that the rvalue of _b_ is the lvalue of _a_. That is, _b_ points to where _a_ lives in memory. Since _b_ knows where variable _a_ lives in memory, _b_ can change its value "indirectly" using the process of indirection.
> 
> Read that paragraph about 50 times and it will make sense.

in annex is this what you mean?

(or [https://drive.google.com/open?id=0B2WLaA0HlUBVVmtRdXBoV0loQzA](https://drive.google.com/open?id=0B2WLaA0HlUBVVmtRdXBoV0loQzA))

![memory.JPG](https://europe1.discourse-cdn.com/arduino/original/4X/f/7/7/f777de4e33171501049fa4e60c217f070c6acfdd.jpeg)

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1105255_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [December 2, 2016, 9:50pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/13 "2016-12-02T21:50:39Z")

</div>

This shows how to use reference or pointer variables in a simple Bubble Sort.

```cpp
int values[] = {11, 25, 69, 32, 21};

void swapElements(int &x, int &y);      // Prototype for reference
void swapPointers(int *x, int *y);      // Prototype for pointer

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

  bubbleSort();
  for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) {
    Serial.println(values[i]);
  }

}

void loop() {
}

void bubbleSort() {
  bool swap;
  int elementCount = sizeof(values) / sizeof(values[0]);
  int temp;
  int i,j;
   
  for(i = 0; i < elementCount - 1; i++) { 
      swap = false;
    
      // loop through numbers falling ahead 
      for(j = 0; j < elementCount - 1 - i; j++) {     
        if(values[j] > values[j+1]) {
//          swapElements(values[j], values[j + 1]);  // Using reference
          swapPointers(&values[j], &values[j + 1]);  // Using pointers
          swap = true;
        }    
      }
      if(swap == false) {
        break;
      }
  }
}

void swapElements(int &x, int &y) {          // Uses references
  int temp;
  temp = x; 
  x = y;   
  y = temp; 
}

void swapPointers(int *x, int *y) {          // Use pointers
  int temp;

  temp = *x; 
  *x = *y;    
  *y = temp; 
}

```

As you can see, they are almost the same. The reference version has less "clutter" in it

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [May 5, 2021, 10:12pm UTC](https://forum.arduino.cc/t/pass-variable-by-reference-pointer-or-by-value/422339/14 "2021-05-05T22:12:22Z")

</div>


