Making a function

I am making a fun little program for my group when we are bored and I am wondering how to use the void task, when I do “void () { … … }” it tells me “expected unqualified-id”

C functions need names. There’s no name. That’s why it’s telling you it expected an ID.

1 Like

Here is an example void function.

void drive(char direction, int speed, int time)
{
if (direction == ‘f’)
{
setmotor(leftdrive,speed);
setmotor(rightdrive,speed);
sleep(time);
setmotor(leftdrive,0);
setmotor(rightdrive,0);
}
if (direction == ‘b’)
{
setmotor(leftdrive,speed * -1);
setmotor(rightdrive,speed * -1);
sleep(time);
setmotor(leftdrive,0);
setmotor(rightdrive,0);
}
}

task main()
{

drive(‘f’,100,1000);
//1000 = 1 second
}

We are working on a functions video to be released soon! Look for it if you need more help!

2 Likes

Here are a couple of points that might help you understand why your code returned an error.

First, In this case, you are writing a function, not a task. A “function” is a piece of code that you define and then call later in your program. When you call a function, you give it some inputs, and it returns some outputs, possibly doing some other stuff along the way. You can read more about functions on Wikipedia here.

Second, ‘void’ is not the name of your function, but rather its return type. In c/c++ and lots of other languages, functions can be defined as follows:

return_type function_name( p1_type p1_name, p2_type p2_name ){
    //function code goes here...
    return some_value;
}

where:

  • function_name is the name of the function
  • p1_type and p2_ type are the type of the first and second parameters, respectively
  • p1_name and p2_ name are the name of the first and second parameters, respectively (you can have as many parameters as you want, separated by commas)
  • return_type is the type of the value that will be returned, in this case some_value. Read more about types in c here.

In the simplest possible case, your function takes no parameters and returns nothing. In this case, your function is basically an abbreviated shortcut to some code that you define. You might want to do this to improve readability, or because you need to call this code in multiple places in your program.

The problem is, we are still required to define a return type, even if our function doesn’t return anything. That’s what the void keyword is for (well, one of the things it’s for - read more here). To define a function that takes no parameters and returns nothing, we can do the following:

void function_name(void){
    //code goes here!
}

(That second void is optional but not a bad idea to include if your function takes no parameters)

3 Likes