VEXcode for experts

Are you able to pass a port as a parameter in a function? If so, how and would it need to be passed by reference? With the season coming to an end soon, we want to spend some more time on programming and help the kids build function libraries. We would like to help them build a function, such as:

void turn(int degree, port p){
pid controls to make a turn based on the degrees passed in and the port specified.
}

This would allow reusability for any port if we could simply call up port p in the function and have it call the port passed into it.

Why not just pass a reference to the motor instead?

This seems like the thing to do to me.


But, if you really want to pass port numbers to functions, there is no special type for ports - the constants PORT1 through PORT22 (yes, port 22, that’s where all the three-wire ports live) are just int32_ts.

So, you could write a function like the following:

void doSomething(int32_t port){
    motor Motor(port);
    //some code to do stuff with the motor you just instantiated goes here
}

and then call it on whatever port you want:

doSomething(PORT3);

But it seems kind of wasteful to have to initialize a new motor object every time you want to move a motor - so I agree it would be a better idea to pass a reference to the motor instead like so:

void doSomething(motor& Motor){
    //some code to do stuff with Motor goes here
}

int main(){
    motor Motor1(PORT1);
    doSomething(Motor1);
}
5 Likes

Perfect. I actually wanted to use a reference, but I was unsure if you could pass a motor type. Thanks so much.