Go Down

Topic: Passing and return variables (Read 501 times) previous topic - next topic

n46130

I want to pass the value of i to half(i) and return the adjusted value of i. Code will not compile in Arduino but runs in the Arduino simulator

Code: [Select]
 
void setup(){
Serial.begin (9600);
}
void loop(){
 
 int i=4;
 Serial.println ("I = input");
 half (i);
 Serial.println (i);
 return ;
}

void half(int i){
 
 i=i/2;
 Serial.println (i);
 return(i);
}

PaulS

Code: [Select]
  return(i);
But, you've said that the function doesn't return a value:
Code: [Select]
void half(int i){
Which is correct?

Nick Gammon

Code: [Select]
half (i);

You aren't using the return value anyway.

You can return the value:

Code: [Select]
void setup()
  {
  Serial.begin (9600);
  }

void loop()
  {
  int i=4;
  Serial.println ("I = input");
  Serial.println (half (i));
  delay (500);
  }

int half (int i)
  {
  return i / 2;
  }


Or, you can half the argument, if you pass it by reference:

Code: [Select]
void setup()
  {
  Serial.begin (9600);
  }

void loop()
  {
  int i=4;
  Serial.println ("I = input");
  half (i);
  Serial.println (i);
  delay (500);
  }

void half (int & i)
  {
  i = i / 2;
  }
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

kf2qd

Your are getting confused with localization of variables.

When you have something like this -

void fun1() {
   int i;
   i=4;
   half(i);    // result just going to the bit bucket...
   print (i);
}

int half(int i) {
  i = i/2;
  return i;
}

you have 2 instances of i. one exists in fun1() and the other one exists in half(int i). and neither is global. and both are completely different variables.

if you want the return value to make it to fun1 you need to call half this way i = half(i). Otherwise the return value just goes to the bit bucket in the shy. So - your return value was just getting thrown out.

For i to have been a global variable it would have had to be defined before any functions and then your code would have worked. Globals have their place, where you need a value available everywhere. but it is poor practice to define all variables as globals, but we can often get away with it because our programs are small.


n46130


Go Up