ROBOTC.net forums
http://www.robotc.net/forums/

Global versus Local Variables within Functions
http://www.robotc.net/forums/viewtopic.php?f=11&t=11708
Page 1 of 1

Author:  MichaelMedford [ Sat Jul 11, 2015 4:11 pm ]
Post subject:  Global versus Local Variables within Functions

Hello there! First time poster. I am playing around with creating functions in ROBOTC and have a couple of questions I was hoping the community could help answer. I didn't want to overload this one post though since each question is a little different, so I'm going to break it up into a few posts

I'm a bit confused how to navigate the difference between global and local variables in ROBOTC. Am I able to execute a function which uses global variables when I call the function? For example:

Code:
bool forwards = true;

bool moveforwards() {
   motor[port1] = 63;
   motor[port2] = -63;

   forwards = true;
   return forwards;
   }

task main() {
   forwards = moveforwards();
   }


Or instead do I have to define a local variable within the function to pass along?

Code:
bool forwards = true;

bool moveforwards() {
   motor[port1] = 63;
   motor[port2] = -63;

   bool forwards_temp = true;
   return forwards_temp;
   }

task main() {
   forwards = moveforwards();
   }


What would happen if I did the 2nd example, but declared the variable name "forwards" within the moveforwards function instead of "forwards_temp"? Would I get a compile error because there are two different variables, one global and one local, being declared with the same name? Or would ROBOTC just take the move recent declaration/assignment as the final one?

Thanks for the help!

Author:  mightor [ Sun Jul 12, 2015 6:46 am ]
Post subject:  Re: Global versus Local Variables within Functions

Hey there,

In your first example you return the value of a variable that is already global in its nature, which is not really necessary.

You *can* have multiple variables with differing scopes (global vs local), but that may lead to bad programming habits, which you should avoid. The standard best practice for variables is: make their scope as limited as possible. That means that if a variables does not need to be global, then make it local. Resort to globals only when you have to.

Also, this is perfectly OK to do:
Code:
bool forwards = true;

bool moveforwards() {
  motor[motorA] = 63;
  motor[motorB] = -63;
  return true;
}

task main() {
  forwards = moveforwards();
}

Author:  MichaelMedford [ Sun Jul 12, 2015 4:41 pm ]
Post subject:  Re: Global versus Local Variables within Functions

Thanks for the info/advice! This helps a lot.

Page 1 of 1 All times are UTC - 5 hours [ DST ]
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/