Beinnging C++ Function

Hello forums, i have specificity made an account on this website for help.

I have recently purchased "Jumping Into C++" and i love it. But i'm having a little of a hard time understand HOW and WHEN to use functions in C++.

Can anybody please explain it to me in a very basic way? i would indeed appreciate it. Thank you.
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();
	//... 
Last edited on
Awesome, Thank you! that is pretty clear. Is there really any differnce in "Void" and "Int" in declaring a function?
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.

Hope this helps.. :)
Last edited on
Thank you, i believe i am understand it a little bit more.
Topic archived. No new replies allowed.