Lesson 92 +10 XP

Void Functions (non-value returning)

Void Functions (Non-Value Returning)

Not every function needs to send a value back. Some just do work - print a message, update a variable, move a player. Those functions use the return type void.

What void means

The classic void hello() function:

void hello() {
  cout << "Hello!";
}
  • void literally means "no type": the function returns nothing.
  • It does its job through side effects: printing, modifying objects, updating state.
  • You simply call it; there is no result to store.

Calling a void function

int main() {
  hello();      // prints "Hello!"
  return 0;
}

Because hello() doesn't return a value, you can't write int x = hello(); - there is nothing to assign.

You can still use return

A void function can end early with a bare return; (no value). It's optional and just exits the function:

void greet(bool nice) {
  if (!nice) {
    return;   // end early
  }
  cout << "Hello";
}

When to use void vs a return value

  • Use void when the function performs an action.
  • Use a return type (like int) when the function computes and hands back a value.

TL;DR

  • void means the function returns no value.
  • Void functions do their work through side effects: printing, modifying, responding.
  • A call to a void function produces nothing to store.
  • A bare return; can end one early.
  • Choose void for actions; choose a return type for values.