Function arguments: by reference or by value?

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
odometer
 
Posts: 98
Joined: Sun Aug 21, 2011 11:01 pm

Function arguments: by reference or by value?

Post by odometer »

Are function arguments passed by reference or by value?

Specifically, if I am passing a numeric argument to a function, what happens if I change it within the function?

Code: Select all

function foo(int x) {
  x--;
  // do some more stuff here
}

int n=5;
foo(n);
// all right, what is the value of n now?

User avatar
adafruit_support_bill
 
Posts: 88096
Joined: Sat Feb 07, 2009 10:11 am

Re: Function arguments: by reference or by value?

Post by adafruit_support_bill »

Integers are pass by value.

User avatar
philba
 
Posts: 387
Joined: Mon Dec 19, 2011 6:59 pm

Re: Function arguments: by reference or by value?

Post by philba »

C is by value but you also get by reference by passing pointers (or an array name). For example:

Code: Select all

void foo(int a[]){
  a[0] = 1;
}

void loop(){
   ...
   int b[10];
   
   b[0] = 0;
   foo(b);
   // b[0] is 1
}

mtbf0
 
Posts: 1645
Joined: Sat Nov 10, 2007 12:59 am

Re: Function arguments: by reference or by value?

Post by mtbf0 »

in c and c++ scalar values are passed by value and arrays and structures and, (in c++), objects are passed by reference. you can, as mentioned, pass pointers in both languages, but c++ has a way to specify pass by reference. in function declarations and prototypes append an ampersand to the parameter type, like so...

Code: Select all

void foo (int& bar);
it's important to remember that the arduino is programmed in c++. this detail has bitten me on the ass at least once. once was prototyping a project on an arduino that was going to run on a tiny2313 in c and spent quite a while trying to figure out why an array with an undeclared dimension in a structure would not compile. maybe not perfect, but perfectly legal in c, but it turns out that all structures in c++ are objects and my struct was not a legal object.

User avatar
philba
 
Posts: 387
Joined: Mon Dec 19, 2011 6:59 pm

Re: Function arguments: by reference or by value?

Post by philba »

It's funny that the Arduino folks never actually say "C++" but rather the "Ardunio Language" as if it's something unique that they invented. Then, of course, they run GCC under the covers. The nice thing is C++, stdio lib, iolib and such mostly works. Makes Arduino so much more than a toy.

This brings up a gripe I have - with the desire to make Arduino for "artists" they try to hide what's going on. I have often been puzzled by some description before realizing what it really is. And, they make you work to find more detailed documentation (like stdio).

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”