Navigation



1.4 — A first look at functions

A function is a sequence of statements designed to do a particular job. You already know that every program must have a function named main(). However, most programs have many functions, and they all work analogously to main.

Often, your program needs to interrupt what it is doing to temporarily do something else. You do this in real life all the time. For example, you might be reading a book when you remember you need to make a phone call. You put a bookmark in your book, make the phone call, and when you are done with the phone call, you return to your book where you left off.

C++ programs work the same way. A program will be executing statements sequentially inside one function when it encounters a function call. A function call is an expression that tells the CPU to interrupt the current function and execute another function. The CPU “puts a bookmark” at the current point of execution, and then calls (executes) the function named in the function call. When the called function terminates, the CPU goes back to the point it bookmarked, and resumes execution.

Here is a sample program that shows how new functions are declared and called:

//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>

// Declaration of function DoPrint()
void DoPrint()
{
    using namespace std;  // we need this in each function that uses cout and endl
    cout << "In DoPrint()" << endl;
}

// Declaration of main()
int main()
{
    using namespace std;  // we need this in each function that uses cout and endl
    cout << "Starting main()" << endl;
    DoPrint(); // This is a function call to DoPrint()
    cout << "Ending main()" << endl;
    return 0;
}

This program produces the following output:

Starting main()
In DoPrint()
Ending main()

This program begins execution at the top of main(), and the first line to be executed prints Starting main(). The second line in main is a function call to DoPrint. At this point, execution of statements in main() is suspended, and the CPU jumps to DoPrint(). The first (and only) line in DoPrint prints In DoPrint(). When DoPrint() terminates, the caller (main()) resumes execution where it left off. Consequently, the next statment executed in main prints Ending main().

Functions can be called multiple times:

//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>

// Declaration of function DoPrint()
void DoPrint()
{
    using namespace std;
    cout << "In DoPrint()" << endl;
}

// Declaration of main()
int main()
{
    using namespace std;
    cout << "Starting main()" << endl;
    DoPrint(); // This is a function call to DoPrint()
    DoPrint(); // This is a function call to DoPrint()
    DoPrint(); // This is a function call to DoPrint()
    cout << "Ending main()" << endl;
    return 0;
}

This program produces the following output:

Starting main()
In DoPrint()
In DoPrint()
In DoPrint()
Ending main()

In this case, main() is interrupted 3 times, once for each call to DoPrint().

Main isn’t the only function that can call other functions. In the following example, DoPrint() calls a second function, DoPrint2().

//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>

void DoPrint2()
{
    using namespace std;
    cout << "In DoPrint2()" << endl;
}

// Declaration of function DoPrint()
void DoPrint()
{
    using namespace std;
    cout << "Starting DoPrint()" << endl;
    DoPrint2(); // This is a function call to DoPrint2()
    DoPrint2(); // This is a function call to DoPrint2()
    cout << "Ending DoPrint()" << endl;
}

// Declaration of main()
int main()
{
    using namespace std;
    cout << "Starting main()" << endl;
    DoPrint(); // This is a function call to DoPrint()
    cout << "Ending main()" << endl;
    return 0;
}

This program produces the following output:

Starting main()
Starting DoPrint()
In DoPrint2()
In DoPrint2()
Ending DoPrint()
Ending main()

Return values

If you remember, when main finishes executing, it returns a value back to the operating system (the caller) by using a return statement. Functions you write can return a single value to their caller as well. We do this by changing the return type of the function in the function’s declaration. A return type of void means the function does not return a value. A return type of int means the function returns an integer value to the caller.

// void means the function does not return a value to the caller
void ReturnNothing()
{
    // This function does not return a value
}

// int means the function returns an integer value to the caller
int Return5()
{
    return 5;
}

Let’s use these functions in a program:

cout << Return5(); // prints 5
cout << Return5() + 2; // prints 7
cout << ReturnNothing(); // This will not compile

In the first statement, Return5() is executed. The function returns the value of 5 back to the caller, which passes that value to cout.

In the second statement, Return5() is executed and returns the value of 5 back to the caller. The expression 5 + 2 is then evaluated to 7. The value of 7 is passed to cout.

In the third statement, ReturnNothing() returns void. It is not valid to pass void to cout, and the compiler will give you an error when you try to compile this line.

One commonly asked question is, “Can my function return multiple values using a return statement?”. The answer is no. Functions can only return a single value using a return statement. However, there are ways to work around the issue, which we will discuss when we get into the in-depth section on functions.

Returning to main

You now have the conceptual tools to understand how the main() function actually works. When the program is executed, the operating system makes a function call to main(). Execution then jumps to the top of main. The statements in main are executed sequentially. Finally, main returns a integer value (usually 0) back to the operating system. This is why main is declared as int main().

Some compilers will let you get away with declaring main as void main(). Technically this is illegal. When these compilers see void main(), they interpret it as:

int main()
{
    // your code here
    return 0;
}

You should always declare main as returning an int and your main function should return 0 (or another integer if there was an error).

Parameters

In the return values subsection, you learned that a function can return a value back to the caller. Parameters are used to allow the caller to pass information to a function! This allows functions to be written to perform generic tasks without having to worry about the specific values used, and leaves the exact values of the variables up to the caller.

This is a case that is best learned by example. Here is an example of a very simple function that adds two numbers together and returns the result to the caller.

//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>

// add takes two integers as parameters, and returns the result of their sum
// add does not care what the exact values of x and y are
int add(int x, int y)
{
    return x + y;
}

int main()
{
    using namespace std;
    // It is the caller of add() that decides the exact values of x and y
    cout << add(4, 5) << endl; // x=4 and y=5 are the parameters
    return 0;
}

When function add() is called, x is assigned the value 4, and y is assigned the value 5. The function evaluates x + y, which is the value 9, and then returns this value to the caller. This value of 9 is then sent to cout to be printed on the screen.

Output:

9

Let’s take a look at a couple of other calls to functions():

//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>

int add(int x, int y)
{
    return x + y;
}

int multiply(int z, int w)
{
    return z * w;
}

int main()
{
    using namespace std;
    cout << add(4, 5) << endl; // evalutes 4 + 5
    cout << add(3, 6) << endl; // evalues 3 + 6
    cout << add(1, 8) << endl; // evalues 1 + 8

    int a = 3;
    int b = 5;
    cout << add(a, b) << endl; // evaluates 3 + 5

    cout << add(1, multiply(2, 3)) << endl; // evalues 1 + (2 * 3)
    cout << add(1, add(2, 3)) << endl; // evalues 1 + (2 + 3)
    return 0;
}

This program produces the output:

9
9
9
8
7
6

The first three statements are straightforward.

The fourth is relatively easy as well:

    int a = 3;
    int b = 5;
    cout << add(a, b) << endl; // evaluates 3 + 5

In this case, add() is called where x = a and y = b. Since a = 3 and b = 5, add(a, b) = add(3, 5), which resolves to 8.

Let’s take a look at the first tricky statement in the bunch:

    cout << add(1, multiply(2, 3)) << endl; // evalues 1 + (2 * 3)

When the CPU tries to call function add(), it assigns x = 1, and y = multiply(2, 3). y is not an integer, it is a function call that needs to be resolved. So before the CPU calls add(), it calls multiply() where z = 2 and w = 3. multiply(2, 3) produces the value of 6, which is assigned to add()’s parameter y. Since x = 1 and y = 6, add(1, 6) is called, which evaluates to 7. The value of 7 is passed to cout.

Or, less verbosely (where the => symbol is used to represent evaluation):
add(1, multiply(2, 3)) => add(1, 6) => 7

The following statement looks tricky because one of the parameters given to add() is another call to add().

    cout << add(1, add(2, 3)) << endl; // evalues 1 + (2 + 3)

But this case works exactly the same as the above case where one of the parameters is a call to multiply().

Before the CPU can evaluate the outer call to add(), it must evaluate the inner call to add(2, 3). add(2, 3) evaluates to 5. Now it can evaluate add(1, 5), which evaluates to the value 6. cout is passed the value 6.

Less verbosely:
add(1, add(2, 3)) => add(1, 5) => 6

Effectively using functions

One of the biggest challenges new programmers encounter (besides learning the language) is learning when and how to use functions effectively. Functions offer a great way to break your program up into manageable and reusable parts, which can then be easily connected together to perform a larger and more complex task. By breaking your program into smaller parts, the overall complexity of the program is reduced, which makes the program both easier to write and to modify.

Typically, when learning C++, you will write a lot of programs that involve 3 subtasks:

  1. Reading inputs from the user
  2. Calculating a value from the inputs
  3. Printing the calculated value

For simple programs, reading inputs from the user can generally be done in main(). However, step #2 is a great candidate for a function. This function should take the user inputs as a parameter, and return the calculated value. The calculated value can then be printed (either directly in main(), or by another function if the calculated value is complex or has special printing requirements).

A good rule of thumb is that each function should perform one (and only one) task. New programmers often write functions that combine steps 2 and 3 together. However, because calculating a value and printing it are two different tasks, this violates the one and only one task guideline. Ideally, a function that calculates a value should return the value to the caller and let the caller decide what to do with the calculated value.

Quiz

1) What’s wrong with this program fragment?

void multiply(int x, int y)
{
    return x * y;
}

int main()
{
    cout << multiply(4, 5) << endl;
    return 0;
}

2) What’s wrong with this program fragment?

int multiply(int x, int y)
{
    int product = x * y;
}

int main()
{
    cout << multiply(4, 5) << endl;
    return 0;
}

3) What value does the following program fragment print?

int add(int x, int y, int z)
{
    return x + y + z;
}

int multiply(int x, int y)
{
    return x * y;
}

int main()

{
    cout << multiply(add(1, 2, 3), 4) << endl;
    return 0;
}

4) Write a function called doubleNumber() that takes one integer parameter and returns double it’s value.

5) Write a complete program that reads an integer from the user (using cin, discussed in section 1.3), doubles it using the doubleNumber() function you wrote for question 4, and then prints the doubled value out to the console.

Quiz Answers

To see these answers, select the area below with your mouse.

1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

5) Show Solution

1.5 — A first look at operators
Index
1.3 — A first look at variables (and cin)

295 comments to 1.4 — A first look at functions

  • SivaSankar

    CAN A USER DEFINED FUNCTION BE INITIALISED INSIDE MAIN()?

    • Slyfvro

      Yes it can but its better to give each required task a different user defined function.It is to make it easier to fix errors.Cause dividing them into chunk will help to isolate errors when they occur but if they are in 1 whole function it would be hard, right?

  • hockey1scool

    what is wrong with this…

    #include

    using namespace std;

    int Return5()
    {
    return 5;
    }

    int main()
    {
    cout << Return5(); // prints 5
    cout << Return5() + 2; // prints 7
    }

    • Slyfvro

      int main()
      {
      cout << Return5(); // prints 5
      cout << "\n";
      cout << Return5() + 2; // prints 7
      }

      Use that.The mistake you have done is not placing a line separation between cout << Return5(); and cout << Return5() + 2,So instead of displaying 5 and 7,it is showing 57.

    • Leopoldus

      Hi, he also could have done this:

      int main()
      {
      cout << Return5()<<endl; // prints 5
      cout << Return5() + 2; // prints 7
      }
      I am wrong?

  • DrSuse

    Declare your function using parameters, then use a different variable for user input in main():

    #include

    int doubleNumber(int x)
    {
    return 2 * x;
    }

    int main()
    {
    using namespace std;
    int a = -1;
    cout << "Enter the number to be doubled: " << endl;
    cin << a;
    cout << a << " doubled is " << doubleNumber(a) << endl;
    return 0;
    }

    The user input is then displayed along with the result.

  • mihirichathurika

    Thank you so much. you explain it simply

  • Jupoopiter

    Superb tutorials!

    I was getting an error on Quiz question 5 because on line 13 I was calling the function like this: doubleNumber() rather than like this: doubleNumber(x).

    Sorry for the stupid question, but can someone explain why the x needs to be there?

    • How did you define the function doubleNumber? It was doubleNumber( int x ) {}, right?
      See, the int x part is the input part of the function – you list all the things that go into the function. You can’t actually specify specific variable names though, you can only specify the name that will be used in the function (can be anything you want, that’s how you’ll refer to the input inside the function), and the type (int, float, string, etc).
      So the reason it’s doubleNumber(x), is because you have to mention which variable to pass to doubleNumber. That way you can also call it like doubleNumber(y) and doubleNumber(z), and it will double the variables y and z.

  • Slyfvro

    It is because when calling the function you also need to specify its correct parameters.Since the doubleNumber(int x) function is not inside int main().the int main() does not know the parameters or even whether int x exists.So you need to tell int main that doubleNumber(int x) is a function with “int x” as its parameter.

  • dj51401

    This is awesome I am only 11 Years old and I find this pretty easy! Thank you for the tutorials

  • toastedsub94

    Ehhh, wow mine was overly complicated.

    int multiply(int x)
    {
    using namespace std;
    int y;
    y = x * 2;
    return y;
    }

    int main()
    {
    using namespace std;
    cout <> x;
    cout << multiply(x) << endl;
    return 0;
    }

  • thebadlizard

    cout << add(1, multiply(2, 3)) << endl; // evalues 1 + (2 * 3)
    cout << add(1, add(2, 3)) << endl; // evalues 1 + (2 + 3)

    Are all integers of "add" functions assigned to x and y, and all integers of "multiply" assigned to z and w?

  • wnn1994

    WHAT’S WRONG WITH MY PROGRAM ?THANK U

    #include “stdafx.h”
    #include
    int doubleNumber(int x)
    {
    return x*2;
    }

    int main()

    {
    using namespace std;
    system(“PAUSE”);
    cout <<"please enter the number:"<>x;
    cout<<doubleNumbe(x)<<endl;
    return 0;
    }

    • MagicToaster

      Hey wnn1994,

      You didn’t use the statement “cin >> x;” to make the “doubleNumber(int x)” function work properly. I suggest you do so. Cheers

    • Zidane

      //Your code:
      //————————————————
      #include “stdafx.h”
      #include
      int doubleNumber(int x)
      {
      return x*2;
      }

      int main()

      {
      using namespace std;
      system(“PAUSE”);
      cout <<"please enter the number:"x;
      cout<<doubleNumbe(x)<<endl;
      return 0;
      }

      —————————————————————
      //CORRECTION:

      #include “stdafx.h”
      #include
      int doubleNumber(int x)
      {
      return x*2;
      }

      int main()

      {
      using namespace std;
      system(“PAUSE”);
      cout <>x;
      cout<<doubleNumber(x)<<endl;
      return 0;
      }

      //___________________________________________________
      //So, I'll point out where there were bugs:
      /* First: You did not include the
      * Second:you made a mess there after asking to enter a number, and you
      * did not put the cin>> command.
      * Third and last: When calling the function doubleNumber(int x) on main()
      * You had a type, you left out the r in Numbe(r).
      * But I’m sure you already figured this out by now ^.^
      */

  • CalebDK

    Quiz 3 doesn’t return anything but instead a compiler error because main() doesn’t have ” using namespace std; “.
    Should be:

    int main()
    {
    using namespace std;
    cout << multiply(add(1, 2, 3), 4) << endl;
    return 0;
    }

  • this was so helpful! thank you very much! :)

  • KADAMA2

    #include

    This is what I typed:
    int user (int x)
    {
    return x;
    }

    int doublen (int x)
    {
    return 2 * x;
    }

    int main()
    {
    using namespace std;
    cout << "Enter a number:" <> user;
    cout << doublen (user);
    return 0;
    }

  • DarkmoonBlade

    /*
    * 2/11/2014
    */
    #include
    #include

    #define spdOfSound 340.29

    using namespace std;

    int calTipe = 0;// all variables
    string ans1;
    double VelReciever = 0.0;
    double VelSource = 0.0;
    double ObservedFreq = 0.0;
    double EmittedFreq= 0.0;

    double CalFreqEmitted (double VelReciever , double VelSource ,double ObservedFreq) // function for calculating the emitted frequency A:
    {
    double FreqEmitted = 0.0;
    calTipe == 1 ? FreqEmitted = ObservedFreq/((spdOfSound+VelReciever)/(spdOfSound-VelSource)) : FreqEmitted = ObservedFreq/((spdOfSound-VelReciever)/(spdOfSound+VelSource));// if statement checks which formula to use depending if the objects move towards or away from each other

    return FreqEmitted;
    }
    double CalFreqObserved (double VelReciever , double VelSource ,double EmittedFreq)// function for calculating the observed frequency B:
    {
    double FreqObserved = 0.0;
    calTipe == 1 ? FreqObserved = ((spdOfSound+VelReciever)/(spdOfSound-VelSource))*EmittedFreq : FreqObserved = ((spdOfSound-VelReciever)/(spdOfSound+VelSource))*EmittedFreq;// if statement checks which formula to use depending if the objects move towards or away from each other

    return FreqObserved;
    }
    double CalVelReciever (double ObservedFreq,double EmittedFreq,double VelSource)// function for calculating the velocity of the reciever C:
    {
    double VelReciever = 0.0;
    calTipe == 1 ? VelReciever = (((ObservedFreq*(spdOfSound-VelSource))/EmittedFreq)-spdOfSound) : VelReciever = (((ObservedFreq*(spdOfSound+VelSource))/EmittedFreq)-spdOfSound)*-1 ;// if statement checks which formula to use depending if the objects move towards or away from each other

    return VelReciever;
    }
    double CalVelSource (double ObservedFreq,double EmittedFreq,double VelReciever)// function for calculating the velocity of the Source D:
    {
    double VelSource = 0.0;
    calTipe == 1 ? VelSource = (((EmittedFreq*(spdOfSound+VelReciever))/ObservedFreq)-spdOfSound)*-1 : VelSource = (((EmittedFreq*(spdOfSound-VelReciever))/ObservedFreq)-spdOfSound);// if statement checks which formula to use depending if the objects move towards or away from each other

    return VelSource;
    }

    int main ()
    {
    char ans = ‘ ‘;// answer variable for the menu . do while loop
    cout << "Welcome to my program to Calculate the dopplereffect hope you enjoy :) … the program is case sensitive "<<endl;

    do // do while loop to loop the program until a certain action is performed
    {
    cout<> ans1;

    ans1 == “yes” ? calTipe = 1 : calTipe = 2 ; // checks if the objects are moving closer or further from each other

    cout<<"nMenu n———————————————————————–"<<endl;
    cout<< "Option A : Calculate the emitted frequency "<<endl;
    cout<< "Option B : Calculate the observed frequency "<<endl;
    cout<< "Option C : Calculate the velocity of the reciever"<<endl;
    cout<< "Option D : Calculate the velocity of the source"<<endl;
    cout<< "Option E : Quit the program"<<endl;
    cout<>ans;

    switch(ans)
    {
    case ‘A’ :
    cout<> VelReciever;

    cout<> VelSource;

    cout<> ObservedFreq;

    cout<<"nThe emitted frequency is: "<< CalFreqEmitted (VelReciever,VelSource,ObservedFreq)<<" Hzn";
    break;

    case 'B' :
    cout<> VelReciever;

    cout<> VelSource;

    cout<> EmittedFreq;

    cout<<"nThe observed frequency is: "<< CalFreqObserved (VelReciever,VelSource,EmittedFreq)<<" Hzn";
    break;

    case 'C':
    cout<> ObservedFreq;

    cout<> EmittedFreq;

    cout<> VelSource;

    cout<< "nThe velocity of the reciever is: "<<CalVelReciever (ObservedFreq,EmittedFreq,VelSource)<<" m.sn";
    break;

    case 'D':
    cout<> ObservedFreq;

    cout<> EmittedFreq;

    cout<> VelReciever;

    cout<< "nThe velocity of the source is: "<< CalVelSource (ObservedFreq,EmittedFreq,VelReciever)<<" m.sn";
    break;
    }
    }
    while (ans != 'E');// stops the loop when E is entered
    return (0);
    }

  • DarkmoonBlade

    why when you submit your code in the comment section (copy and paste it) the whole program changes allot of things are left out as you can see in my program in the previous comment ???

  • kenwhite23

    Not sure whats wrong with my code. I know that its wrong even though it compiles correctly as when i input 23 it doubles to 83214 or any random number just not sure why, I rewrote the code in several other ways that worked, So i did get the quiz done in a way that is successful now i just want to understand why it is that this didnt work, any input is greatly appreciated!

    #include <iostream>
    #include <windows.h>
    using namespace std;

    int user(int x)
    {
    cout << "Pick a number to double: " << endl;
    cin >> x;
    }

    int doublenumber(int x)
    {
    return 2 * x;
    }

    int main()
    {
    int x;
    user(x);
    cout << doublenumber(x) << endl;
    system("pause"); //can also be replaced with getchar() to make portable
    return 0;
    }

    • kenwhite23

      Figured it out, i needed to add the return x into function user() and then adjust main() to cout << doublenumber(user(x)) << endl;

      Here is the working version!
      #include
      #include
      using namespace std;

      int user(int x)
      {
      cout << "Pick a number to double: " <> x;
      return x;
      }

      int doublenumber(int x)
      {
      return 2 * x;
      }

      int main()
      {
      int x;
      cout << doublenumber(user(x)) << endl;
      system("pause"); //can also be replaced with getchar() to make portable
      return 0;
      }

  • NICK JACK

    HEY, I GOT A PROB. WHENEVER COMPILER REACHES TO COUT IT GIVES A RED LINE N PRGRM DOESN’T COMPILE HELP…
    I AM USING DEVC++ IDE PLZZ HLPPP

  • mailla

    Hi, thankyou for this wonderful site. Im a begginer and its helping me a lot. Can you help me with this question please..
    Write a function prototype (in c++) for a function which accepts two integers as parameters and returns their difference?
    thanks in advance

  • sarsiz

    #include “stdafx.h”
    #include
    using namespace std;

    int Return5()
    {
    using namespace std;

    cout << Return5(); // prints 5
    return 5;
    }
    Please someone tell me what is the error in the above. Because whenever I try to run it shows me an error. I have VB C++ 2010

    • black_ant

      where is your main function?

      #include “stdafx.h”
      #include iostream

      using namespace std;

      int Return5()
      {
      return 5;
      }

      int main()
      {
      int return_value;
      return_value = Return5();
      cout<< return_value;
      return 0;
      }

  • black_ant

    why does a function need to return a value to the operating system? anyone can explain this to me? thanks

  • aborods

    Nice topic, I like it.

  • Jeevesh

    Hi,

    I am new here and following up really well.
    I just did this in Xcode

    #include

    int doubleNumber (int x)
    {
    return 2 * x;
    }

    int main()
    {
    using namespace std;
    cout <> a;
    cout << "Your Result is " << doubleNumber(a) << endl;
    return 0;
    }

    Now, after i enter a value, i get nothing. When i stop the program, i get message :

    "Program ended with exit code: 9"

    Can you help me on this.

  • Jeevesh

    The code is actually like this.

    #include

    int doubleNumber (int x)
    {
    return 2 * x;
    }

    int main()
    {
    using namespace std;
    cout >> “Please Enter Your Number” >> endl;
    int a = 0;
    cin >> a;
    cout << "Your Result is " << doubleNumber(a) << endl;
    return 0;
    }

  • Jeevesh

    Please ignore my issue… it was just an issue of using ‘Enter’ from my NumPad rather than the one in the alpha section. Please ignore.
    Thanks.

  • papagym177

    Why does Alex write that “using namespace std;” needs to be used with each function that includes cout & endl.

    When all that you need to do is use it once in every C++ program.

    I usually place it under any include headers.

You must be logged in to post a comment.