Variable Scope

I know its pretty late asking these questions, but we haven’t gotten
to building a competition port dongle yet and I have a nagging question
on variable scope within the 3 WPI functions (Initialize, Autonomous,
Operator).

The kids have been practicing with code laid out like this:
main()
{
[INDENT] int someVariable;
while (1)
{
[INDENT] doSomethingTo(someVariable);
}[/INDENT]
}
[/INDENT]
And they have been assuming that someVariable will retain its
value each time it loops.

Two questions on this, if they write the same kind of code in either
the Autonomous() or OperatorControl() functions:

- Will the forever loops break the background competition port monitoring
  task?
  • How do I define a variable that retains its value when Autonomous()
    or OperatorControl() loops?

Thanks,

-Bill
Team 2085

WPILib will automatically break the program out of Autonomous() when the operator control period starts. Even if you have an infinite loop in your autonomous function it will put you into the OperatorControl() function when the autonomous period ends. It will not break you out of the Initialize() function which is where you probably want to be initializing things like cameras, gyros, etc.

The variable scoping is just as you described and follows normal C rules. However those variables declared as locals in the Autonomous(), OperatorControl() or Initialize() functions will not be available to each other or to other functions (unless passed as arguments).

To make variables that are available between functions they need to be global in scope - declared outside of any functions. And you need extern declarations for them somewhere, probably in a header file.

Also, you should not put anything in the main function for a competition program - but an empty main function needs to be there to satisfy a linker requirement.

If you are using EasyC then go to the Main() routine and create variables in the Globals block.