Placing RobotC defined functions at the end of your program?

Does this work in RobotC? I tried it on Robot Virtual Worlds and it seems to compile and run okay, but I haven’t tried it on a physical robot.

I recently learned that C++ allows you to place something called “function prototypes” near the top of your program, before the main task. This allows you to then define the function at the end of the program, after the main task. So instead of loading up the top of your program with lots of defined functions, you can just place these one line “function prototypes” at the top and put all the corresponding defined functions at the end.

Here’s what a function prototype looks like:

void turnLeft();

And so, at the bottom of your program, you fully define the function as usual, like this:

void turnLeft()
	motor[motorB] = 100;
	motor[motorC] = -100;

I sometimes create defined functions to help newbies learn to code a robot, but having reams of defined functions at the top of the program can be somewhat daunting to kids who are new to code, so I thought this function prototype thing might come in handy. It also makes it easier if all you want to do is print out the code and not have 10 pages of defined functions come out every time you print.

But, again, I don’t know for sure that this will work on a physical robot.

Yes, this is allowed. It is a standard C practice.

This really comes down to how the RobotC compiler works. A standard C compiler won’t let you reference a function it hasn’t “seen” during parsing hence the need for a prototype. Typically you would create what’s called a header file which is then brought into the c file through a #include directive.

void turnLeft();

#include “main.h”

void turnLeft()

With more complex C programs the scope of your functions is important and sometimes a prototype might be contained within the c file rather than the header file. The extern keyword also provides a mechanism for telling the compiler to go look elsewhere. Really more modern languages are better at dealing with scope but understanding how C compilers work and why newer language developments needed to improve on this is quite important for CS students to learn.

The compiler will give you a warning but it will often allow compilation.

Okay, cool. I’m glad I asked about this.

Best to teach good programming practice!