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.