Search code examples
c++typesvoid

What is the purpose of functions which return void?


void f() means that f returns nothing. If void returns nothing, then why we use it? What is the main purpose of void?


Solution

  • When C was invented the convention was that, if you didn't specify the return type, the compiler automatically inferred that you wanted to return an int (and the same holds for parameters).

    But often you write functions that do stuff and don't need to return anything (think e.g. about a function that just prints something on the screen); for this reason, it was decided that, to specify that you don't want to return anything at all, you have to use the void keyword as "return type".


    Keep in mind that void serves also other purposes; in particular:

    • if you specify it as the list of parameters to a functions, it means that the function takes no parameters; this was needed in C, because a function declaration without parameters meant to the compiler that the parameter list was simply left unspecified. In C++ this is no longer needed, since an empty parameters list means that no parameter is allowed for the function;

    • void also has an important role in pointers; void * (and its variations) means "pointer to something left unspecified". This is useful if you have to write functions that must store/pass pointers around without actually using them (only at the end, to actually use the pointer, a cast to the appropriate type is needed).

    • also, a cast to (void) is often used to mark a value as deliberately unused, suppressing compiler warnings.

      int somefunction(int a, int b, int c)
      {
          (void)c; // c is reserved for future usage, kill the "unused parameter" warning
          return a+b;
      }