Friday, July 31, 2009

What does the VOID function in c++ do?

In a strict, arguably pedantic way, everyone here is wrong.





A void function returns *type* void but since functions return values, not types, nothing is returned. However there are some curious uses, mostly involving templates, where there are some applications.





Just to blow some minds:





#include %26lt;iostream%26gt;





using namespace std;








void foo()


{


cout %26lt;%26lt; "hello world\n";


}








void bar()


{


return foo();


}








int main(int argc, char *argv[])


{


bar();


}





Didn't expect that to compile and work, did ya?

What does the VOID function in c++ do?
David has part of the answer....in fact not only is void used to signify that you are not going to return a value but it can also (and is done commonly) be used as a way to signify a incoming/outgoing value (thru: void *) that has no defined type at runtime...think of it as a generic intrinsic type that when you do decide to use its value you will explicitly cast this void* type to whatever you like.
Reply:Nothing, that why it is void. If you look at a language like Pascal, which has functions (snippets of code that return a value) and subroutines (code that doesn't return anything) there is no void type. The first thing in a function header is a return type, since C++ only has functions to specify you aren't returning a value you put the void keyword.


eg.


int x = mymathfunction(); // fine if mymathfunction returns int,


error if the return type is void.





void is can also be used in a parameter list that takes nothing. eg.


void printmenu(void)


{ //code


}








In case you are wondering why main has a return type in C++, it is because it returns an integer value to the operating system.
Reply:void just means that the function does not return a value. If the function is just used to perform some action but does not need to return a status it is declared as void.


No comments:

Post a Comment