A rule of thumb for beginners: If you find yourself writing similar code over and over again, you should be using a function. You should also be using functions if it benefits your design and decouples things from one another.
For instance (without getting too technical), let's say I want to play a simple song, which is composed of beeps.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main() {
beep(110, 250);
beep(220, 250);
beep(440, 250);
beep(880, 250);
//do something else here
//and play the song again
beep(110, 250);
beep(220, 250);
beep(440, 250);
beep(880, 250);
//...
Instead of copy and pasting the same code twice, you could write a function to play the song:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void playSong() {
beep(110, 250);
beep(220, 250);
beep(440, 250);
beep(880, 250);
}
int main() {
playSong();
//do something else here
//and play the song again
playSong();
//...
Yes they are different. It's something to do with the return type.
1 2 3 4 5 6
// returns an integer value to the computer
// if its 0 then it means that the program ran error free
// if its a non-zero then the opposite is true
int main()
In functions return types don't send it to the computer but to your main program.
if you want to learn fast there are a lot of C++ vid tutorial in youtube. I suggest you watch them while reading the book.
Yes, void means return nothing. int means return an integer.
In main function, if you write int (integer):
1 2 3 4 5 6 7
int main()
{
.... // do something
return 0; // then you must return some integer. Here returning 0 means telling the
// compiler that every thing happened fine.
}
However in functions other than main, you can also return other stuff...
For example:
1 2 3 4 5 6
int add(int a, int b) // return-type is int
{
int sum = a + b;
return sum; // returning an integer
}
If you are returning something, then you can't write void as a return type.