C++ 7. Functions (and namespace)

In part 6 you learned about basic arithmetic in C++. In this article you will be reading about functions. Before that, however, I want to talk a little about namespace std.

 

Namespace

Every time we want to print out something to the screen, we write std::cout, right? This is a quote from part 1:

cout belongs to the namespace std. By typing std::cout, we are telling the computer that we want to use a name, cout, that belongs to std.

 I don't know about you, but I find the code to look rather messy with a lot of std:: everywhere. There are two ways to I'd like to present to clean up the code a little.

 

1. using namespace std;

Example:

#include <iostream>
using namespace std;

int main() {
	cout << "frog i am ribbit" << endl;
}

This outputs "frog i am ribbit" to the screen. using namespace std enables a program to use all the names in any standard C++ header (like iostream in this example). This is generally considered bad practice, because if two libraries have the same name for a function, and you decide to use using namespace for both:

using namespace foo;
using namespace bar;

then you've got a conflict. How is the compiler going to know what which one to use? The code is going to compile, but it might call the wrong function. That's very bad.

 

2. using std::cout;

Example:

#include <iostream>
using std::cout;
using std::endl;

int main() {
	cout << "frog i am ribbit" << endl;
}

Instead of using the whole namespace, we can choose to only be using specific functions. In the example above, cout and endl are being used. If we want a user to input a value with std::cin, we would need the std:: in our code, since we're not using std::cin.

That being said, for the simplicity of these articles, I will use stick with the first option from now on, and make sure there's no conflicts. Great, now we can move on to functions.

 

Functions

A program is normally made up of a bunch of functions. So far, we have only used one function, the main function. The main function is the starting point for all other functions, every program must have a main function in order to start.

#include <iostream>
using namespace std;

void talk() {
	cout << "frog i am ribbit" << endl;
}

int main() {
	talk();
}

This program consists of two functions, main and talk. Notice how main starts with int and talk starts with void. Functions can return values, and they have to know what data type they are going to return. main return integers, and talk return void. Void simply means that it doesn't return anything, all talk does is printing out a text. Recall from part 1 that main returns 0 to indicate that the program has terminated successfully. The return 0; line can be omitted since the program assumes it's been terminated successfully anyway if it comes to that point (return 0 would be the last line of the program).

To call the function talk, we simply type the functions name talk() along with it's parentheses and the program will jump to that function, execute whatever is found inside the functions body.

I should mention that the order here is important. I put the function talk above main on purpose. A program is read line by line, so if main was placed above talk the program wouldn't know what we're referring to when we want to call talk, it wouldn't know that talk exists yet.

To have main at the top, this is how we do it:

#include <iostream>
using namespace std;

void talk();

int main() {
	talk();
}

void talk() {
	cout << "frog i am ribbit" << endl;
}

void talk(); above the main function is called a prototype. It tells the compiler that we have a function named talk somewhere in our code, so when we call talk(), we don't want to see a lot of errors, because now you're aware that it exists, so find it and execute it instead of complaining.

 

Parameters

A parameter is additional information a function needs in order to work. Let's modify our talk function again.

#include <iostream>
using namespace std;

void talk(int);

int main() {
	talk(4);
}

void talk(int x) {
	cout << "frog i am ribbit, am " << x << " yers old" << endl;
}

The output now is: frog i am ribbit, am 4 yers old".

Look at the talk function now, inside the parentheses we have "int x". By typing int x inside the parentheses, the function expects us to pass an int to it. The int that is being passed can then be used inside that function. In the prototype we only typed int and left out the identifier (x). If you want, you can type the identifier in the prototype as well if it makes it clearer for you. It's nothing wrong with that, the compiler just doesn't care and will ignore it.

What if you want to pass two parameters? Then you separate them with a comma. It's as simple as that:

#include <iostream>
using namespace std;

void talk(int, int);

int main() {
	talk(4, 2);
}

void talk(int x, int y) {
	cout << "frog i am ribbit, am " << x << " yers old and i eat "
 		<<  y << " flies and a pie" << endl;
}

This will output: frog i am ribbit, am 4 yers old and i eat 2 flies and a pie".

Separate with comma in the prototype, separate with comma in the function call, separate with comma in the actual function header. You can use how many parameters as you wish, with any data type. It doesn't have to be integers.

 

Returning a value

As said, a functions can return values. Imagine the scenario where you're walking in the city, and suddenly you see two groups of frogs. You immediately know that you just have to go home and write a function in C++ that can add the two groups of frogs to find out the total amount of frogs. Here's a way to do it:

#include <iostream>
using namespace std;

int addFrogs(int, int);

int main() {
	int totalFrogs = addFrogs(3, 5);
	cout << "Frogs: " << totalFrogs << endl;
}

int addFrogs(int group1, int group2) {
	int sum = group1 + group2;
	return sum;
}

This will output: Frogs: 8

The function addFrogs takes two parameters, two integers, group1 and group2. It also returns a value, an int. Inside the functions body, group 1 and group2 are added together and stored in a new int sumsum is then returned.

In the main function we declare an int with the identifier totalFrogs. Note how we can assign it the function addFrogs. The addFrogs is first being executed, the parameters are fed with 3 and 5, and the sum is 8. This number is then returned by the addFrogs, therefore our variable totalFrogs now contains 8.

 

Congratulations! You're now an expert on functions.

Enjoyed this article? Give the teacher an apple.

cookie

0

Author

authors profile photo

Articles with similar tags

Comments