How do you use void?

I’ve been using arduino for few years now and I still can’t use void can someone educate me?

void has three meanings:


Meaning #1, when used as the return type of a function:

void setup()

This means ‘this function does not return any values’, hence it is used for functions like setup and loop, which do not have a return value.


Meaning #2, when used as in the brackets of a function declaration or function definition:

void setup(void)

This means ‘this function does not accept any arguments’.

There are slightly different rules for this between C and C++:

In C++, not putting anything in the brackets of a function definition/declaration also means ‘this function does not accept any arguments’.

However, in C, not putting anything in the brackets technically means ‘this function has an unspecified number of arguments’ and putting void between the brackets means ‘this function does not accept any arguments’.

(Personally I like to always put void in the brackets of my function definitions because I like how explicit it is and how it makes function definitions/declarations very distinct from function calls.)


And finally meaning #3, void *.

A void * (‘void pointer’ or ‘pointer to void’) means a generic pointer to an unspecified type.
This is used when the type that the pointer points to cannot be known ahead of time.
It’s most well known use is probably in the malloc and free functions.
malloc allocates a block of memory and then returns a void * to that block of memory.
free takes a void * to a block of memory allocated by malloc and deallocates it.

In general it’s better to avoid void * as there’s usually a better option.
void * should only be used if you’re 100% sure you know what you’re doing.

4 Likes

How do I use a custom void

What’s a ‘custom void’ ?

Like void shoot extra words

void shoot() {
  if (player.inTheWay()) {
    player.isDead(true);
  }
}

Like this? it simply means the code doesn’t return a value. As opposed to:

bool isDead() {
  if (player.inTheWay()) {
    return true;
  }
  else {
    return false;
  }
}
2 Likes