When I define a method below where I call it, RobotC, although it compiles, puts red x’s next to where I call the method, saying that it is an undefined procedure, global subroutine assumed. In the method definition, it puts a yellow x saying that the method is unreferenced, meaning it has not been called. When I move the method definition above, then everything is fine. Why is this so? In java, it doesn’t matter where you define methods.
In C, code is run from top to bottom. If a function is called above its definition, the processor doesn’t yet know what the function called is actually supposed to do. If you want/need a function below its calls, you can use a function prototype, which tells the processor, “Hey, this will be a thing, but I’m not going to tell you about it yet.” (Kind of like my math teacher). It looks like this:
void foo(int arg);
foo(12);
void foo(int arg) {
motor[Mtr] = arg;
}
You don’t need to do this, and I’m not sure if prototyping hurts performance, but it’s an option. Personally, I like just putting all functions at the top, sorted by what they do and what they’re used for. Then again, I started with RobotC and moved to C and C++, so I don’t know anything else.
^
I use different files to keep things more organized, and it also eliminates this issue so long as the reference to the functions page is above everything else.
Thanks, does anyone know if the prototyping does affect performance?
It has no effect on performance.
When working with standard compilers (ie. C programming, not ROBOTC programming) it’s good practice to always use function prototypes.
That’s good to know! I will start using prototypes.