hello. I am learning C++ by reading books, primarily C++ Primer Plus 5th edition, and watching tutorials on YouTube.
recently i started to learn about the void function and i ran into a brick wall. for some reason i simply just don't understand what it is or how and when to use it. for example in the book it says:
"Other functions take no arguments. For example, one of the C libraries (the one associated with the stdlib.h header file) has a rand() function that has no arguments and that returns a random integer. Its prototype looks like this:
int rand(void); // prototype of a function that takes no arguments
The keyword void explicitly indicates that the function takes no arguments. If you omit void and leave the parentheses empty, C++ interprets this as an implicit declaration that there are no arguments. You could use the function this way:
myGuess = rand(); // function call with no arguments"
So what I'm looking for is a simple explanation of void, a different way of explaining it, and some example code with comments to explain.
If you need more information on what i don't understand just leave a comment and ill reply.
Sorry if this seems like a dumb request but for some reason void just goes right past me.
void is nothing (in C++).
The void in the parenthesis are from C. In C a function with empty parentheses could have any number of parameters. In C++ it doesn't make any difference.
in C++
int rand()
works just like:
int rand(void)
If you still see people doing this in actual C++ code they're probably doing it because of personal preference since C
or they're work place has special rules for functions etc.
As already said, technically, in C++: int rand(void); is equivalent to int rand(); because both them take nothing as argument.
It's preferred to use int rand(void); as you interpret the same thing in C and C++ (in C standard says that if a function mustn't take any parameter, you must specify it using the void keyword).
thanks guys that cleared things up for me. now that this rock is out of my way i can continue learning.