I have been programming for ages in VB and am just getting into C so please, I apologize if I state things wrong. I am just getting into it deeply.
What I want to do is pass parameter variables to a function and have it modify them. I don't want to declare them globally as they are used over and over through a heck of a lot of functions and I don't want their scope changing.
void subOne(){
int v1 = 10;
int v2 = 100;
int v3 = foo(v1,v2);
Serial.println(v1);
Serial.println(v3 );
}
int foo(int bar1, int bar2){
bar1 = bar1 + bar2;
return (bar2 - bar1);
}
I know, its stupid code, but it represents in a brief manner what I want to do. Since I am returning a value from the function, I also need a 2nd return (actually in reality about 6). In VB I can set up the function declaration with variables with the byref modifier so that any changes to the variable inside the function are returned to the calling routine or byval so the parameter variables are protected from change.
How do I do that on the Arduino C? Set up a function so that changes to the passed variables are returned to the caller?
int foo(int & bar1, int & bar2){
int foo(int& bar1, int bar2){
Note that
int &bar1;
int & bar1;
int& bar1;
all mean the same thing. The position of the & with respect to the type and with respect to the name doesn't matter TO THE COMPILER. It matters to people, though. Putting the & near the type makes it obvious that the type is reference to int, but then the variable name stands there alone. Putting the & near the name makes it obvious, when looking at the name, that the variable is a reference.
Pick one style (I prefer the & with the name), and stick with it.
Graynomad:
Just to elaborate, the & means "address of" so
int& bar1
means that the function gets the address of bar1 and can therefore directly access it.
No. It means it's passed by reference. The & operator only means "address of" in different situations.
int bar; // bar is an int
int& foo = bar; // foo is a reference to bar. If you change foo, bar also changes and vice versa
int* bat = &bar; /// bat is a pointer to bar. You have to deference it to change bar
bat; // address of bar
foo; // bar itself
&bar; // address of bar
&foo; // address of bar