-
question on void
what exactly does void do? i have seen it used in the tutorials but cant find where it explains it.
eg:
Code:
#include <stdio.h>
void playgame();
void loadgame();
void playmultiplayer();
int main()
{
int input;
printf( "1. Play game\n" );
printf( "2. Load game\n" );
printf( "3. Play multiplayer\n" );
printf( "4. Exit\n" );
printf( "Selection: " );
scanf( "%d", &input );
switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
printf( "Thanks for playing!\n" );
break;
default:
printf( "Bad input, quitting!\n" );
break;
}
getchar();
}
from the tutorials
or similiar or other uses, i really dont understand what it does.
thanks
-
It is being used to declare a couple of functions that do not return a value.
-
Those are functions that declared in your main file.
To get a better understanding on this, you can treat these as subroutines.
So if you look clearly, you'll see that there're 3 subrountines defined.
1. play game
2. load game
3. play multiplayer
Each subroutine contains different logic. It's pretty obvious that the playgame routine will allow you to play the game. The loadgame routine will load the game for you, and the playmultiplayer routine will allow you to play with 1 or more players.
-
In C++, you have to list a return type for your functions. If your function does not return anything, then you signify that with "void", which means "nothing" or "an absence of value".
-
It means, when you call a function, you can do this
loadgame();
Whereas if the function returned anything other than void, you would normally want to do this
anAnswer = loadgame();
-
Of course, if the function doesn't have a void return type, you can ignore the return value and treat it as if it returned void:
Code:
int function();
function();
A void function doesn't have to have a return statement. It can, but if it does, return isn't followed by anything:
Code:
void function() {
/* ... */
if(something) return;
/* ... */
}
-
You use functions of the type 'void' if you don't need an output value. For example if you have a function that only prints some text to the screen, you would use type 'void', because you don't need a return value.
-
void is "not a type", the "non-type". Void basically says, there's nothing here. Therefore, a function returning void returns nothing, and a pointer to void points to nothing in particular (it's just an address).
-
thanks a heap. all u ppl here are really helpful.