Thursday, April 14, 2011

c++ functions returning void

I'm busy with exams now but I wanted to do a quick update on my blog after realizing how long its been since my last update ><

Anyways this post is about something that isn't seen too-often in c++ so might not be known to some people; c++ void functions can return things, as long as the type is void.

That means all of these are valid to do in c++:

void foo1 {}
void foo2 { return; }
void foo3 { return (void)0; }
void foo4 { return (void)1.1; }
void foo5 { return (void)(cout << "hello world"); }
void foo6 { return foo5(); }

You might think these are useless, but in some cases you might find it aesthetically pleasing to use one of the above styles in your code.

For example, in an emulator you can have an opcode execute function for your interpreter that looks something like:

void opExecute {
unsigned char opcode = fetch();
switch(opcode) {
case 0x84: return ADD();
case 0x62: return SUB();
case 0x34: return BR();

In this case it looks aesthetically pleasing to be returning a void function.

Another reason it might be useful is because it allows you to do in 1 statement what would otherwise take 2 statements.
Consider this code:

void foo() {
if (cond) { cout << "hello world"; return; }
//... do some code

The above if-statement needs brackets around it because it's body has 2 statements in it. But if you cast to void you can combine both statements into one and not need the brackets like so:

void foo() {
if (cond) return (void)(cout << "hello world");
//... do some code

In terms of clarity and length, the first way was better; but sometimes there are situations where you want to keep things as 1 statement to prevent possible errors (like when you're creating macros), so knowing that you can do stuff like this might be useful.


  1. Do you happen to know the chapter and verse of the standard that says this behavior is allowed? Thanks!

    1. Hi Jimmy,
      In the n3242 draft of the standard, its in section 3.9.1, paragraph 9.

      "The void type has an empty set of values. The void type is an incomplete type that cannot be completed. It
      is used as the return type for functions that do not return a value. Any expression can be explicitly converted
      to type cv void (5.4). An expression of type void shall be used only as an expression statement (6.2), as an
      operand of a comma expression (5.18), as a second or third operand of ?: (5.16), as the operand of typeid,
      or as the expression in a return statement (6.6.3) for a function with the return type void."