Jump to content

Intro To C++/Functions

From Wikibooks, open books for an open world

In C++ and many other languages, you will want to create and use various functions. Think of functions as a box. You will (most of the time) put something in, and then something else will come out. If you remember functions from math, it is practically the same thing. Let's take a look at this example:

int Sum(int a, int b)
{
    int SumOfAandB = a + b;
    return SumOfAandB;
}

int main()
{
    int left = 4, right = 8;
    int SumOfLeftAndRight = Sum(left, right);
    cout<<SumOfLeftAndRight<<endl;
    return 0;
}

So first, notice that i placed the new block of code Sum before the main function. That is because during compilation time, the compiler has to know where the functions are before they are called. So if i placed it after the main function, it wouldn't compile, and it would throw an error.

Now look at the very first line, int Sum(int a, int b). Int means that the return value will be an integer value, Sum is the name of the function (for when we call it), and (int a, int b) simply means that there will be two integers that need to be used as arguments when you call the function.

Let's look at the main function. First, we define to integer variables, left which equals 4, and right which equals 8. Then we create a new variable called SumOfLeftAndRight, and set it equal Sum(left, right)? Simply put, it calls the function, sets a equal to left, and b equal to right. Now inside the new function, it creates a new integer SumOfAandB and sets it equal to a + b, which is the same thing as left + right, then it returns the value of SumOfAandB. So whatever the new function returns, it sets that equal to SumOfLeftAndRight in our main function. That is how the return value works. It returns whatever value you set it to return. Just be sure that type of value you return matches the type you defined the function as. That is why we defined Sum as an integer function. Then it counts SumOfLeftAndRight, which is equal to 12.

You can do different types of things, it doesn't just have to add things up, it can be used to compare certain things, maybe type certain things out. Whatever you can do in the main function, you can do in your own functions. But be aware, if we create a variable inside of the main function, we are not able to access that variable in any other functions, since that variable is local to the main function. That is also vice-versa with your own functions and main.