Search

1.4 — A first look at functions and return values

A function is a reusable sequence of statements designed to do a particular job. You already know that every program must have a function named main() (which is where the program starts execution). However, most programs use many functions.

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.

The function initiating the function call is called the caller, and the function being called is the callee or called function.

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

This program produces the following output:

Starting main()
In doPrint()
Ending main()

This program begins execution at the top of function main(), and the first line to be executed prints Starting main(). The second line in main() is a function call to the function 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 statement executed in main prints Ending main().

Note that function calls are made by using the function name, plus an empty set of parenthesis (). We’ll talk about what this set of parenthesis is in the next lesson. For now, just note that if you forget them, your program may not compile (and if it does, the function will not be called as expected).

Rule: Don’t forget to include parenthesis () when making a function call.

Return values

When the main() function finishes executing, it returns an integer value (typically 0) back to the operating system (the caller) by using a return statement.

When you write your own functions, you get to decide whether a given function will return a value to the caller or not. This is done by setting the return type of the function in the function’s definition. The return type is the type declared before the function name. Note that the return type does not indicate what specific value will be returned. It only indicates what type of value will be returned.

Then, inside the called function, we use a return statement to indicate the specific value being returned to the caller. The actual value returned from a function is called the return value.

Let’s take a look at a simple function that returns an integer value, and a sample program that calls it:

In the first function call of return5(), the function returns the value of 5 back to the caller, which passes that value to std::cout to be output.

In the second function call of return5(), the function 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 to be output.

In the third function call of return5(), the function returns the value of 5 back to the caller. However, main() does nothing with the return value so nothing further happens (the return value is ignored).

Note: Return values will not be printed unless the caller sends them to std::cout. In the last case above, the return value is not sent to std::cout, so nothing is printed.

Return values of type void

Functions are not required to return a value. To tell the compiler that a function does not return a value, a return type of void is used. Let’s look at the doPrint() function from the program above:

This function has a return type of void, indicating that it does not return a value to the caller. Because it does not return a value, no return statement is needed.

Here’s another example of a function that returns void, and a sample program that calls it:

In the first function call to returnNothing(), the function prints “Hi” and then returns nothing back to the caller. Control returns to main() and the program proceeds.

The second function call to returnNothing() won’t even compile. Function returnNothing() has a void return type, meaning it doesn’t return a value. However, function main() is trying to send this nothing value to std::cout to be printed. std::cout can’t handle “nothing” values, as it doesn’t know what to do with them (what value would it output?). Consequently, the compiler will flag this as an error. You’ll need to comment out this line of code in order to make your code compile.

The only valid thing you can do with void return values is ignore them.

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 an integer value (usually 0) back to the operating system. This is why main is defined as int main().

Why return a value back to the operating system? This value is called a status code, and it tells the operating system (and any other programs that called yours) whether your program executed successfully or not. By consensus, a return value of 0 means success, and a positive return value means failure.

Note that the C++ standard explicitly specifies that main() must return an int. However, if you do not provide a return statement in main, the compiler will return 0 on your behalf. That said, it is best practice to explicitly return a value from main, both to show your intent, and for consistency with other functions (which will not let you omit the return value).

For now, you should also define your main() function at the bottom of your code file. We’ll talk about why shortly, in section 1.7 -- Forward Declarations.

A few additional notes about return values

First, if a function has a non-void return type, it must return a value of that type (using a return statement). The only exception to this rule is for function main(), which will assume a return value of 0 if one is not explicitly provided.

Second, when a return statement is reached in a function, the function returns back to the caller immediately at that point. Any additional code in the function is ignored.

A function can only return a single value back to the caller. The function may, however, use any logic at its disposal to determine which specific value to return. It may return a single number (return 5). It may return the value of a variable or an expression (both of which evaluate to a single value). Or it may pick a single value from a set of possible values (which is still just a single value).

There are ways to work around only being able to return a single value back to the caller, which we will discuss when we get into the in-depth section on functions.

Finally, note that a function is free to define what its return value means. Some functions use return values as status codes, to indicate whether they succeeded or failed. Other functions return a calculated or selected value. Other functions return nothing. What the function returns and the meaning of that value is defined by the function’s author. Because of the wide variety of possibilities here, it’s a good idea to leave a comment on your functions indicating not just what they return, but also what the return value means.

Reusing functions

The same function can be called multiple times, which is useful if you need to do something more than once.

This program produces the following output:

Enter an integer: 5
Enter an integer: 7
5 + 7 = 12

In this case, main() is interrupted 2 times, once for each call to getValueFromUser(). Note that in both cases, the value read into variable a is passed back to main() via the function’s return value and then assigned to variable x or y!

Note that main() isn’t the only function that can call other functions. Any function can call another function!

This program produces the following output:

Starting main()
A
B
Ending main()

Nested functions

Functions can not be defined inside other functions (called nesting) in C++. The following program is not legal:

The proper way to write the above program is:

Quiz time

Inspect the following programs and state what they output, or whether they will not compile.

1a)

Show Solution

1b)

Show Solution

1c)

Show Solution

1d)

Show Solution

1e)

Show Solution

1f)

Show Solution

1g)

Show Solution

1h) Extra credit:

Show Solution

1.4a -- A first look at function parameters and arguments
Index
1.3a -- A first look at cout, cin, and endl

446 comments to 1.4 — A first look at functions and return values

  • anyone please tells me why my program didn’t work.
    If it had something wrong, please help me to fix it.

    • Alex

      1) You never defined variables x and y
      2) Your functions return void, but should be returning the values x and y back to the caller so that main() can use them.

    • Kevin

      Correct Me if im wrong teacher! I just learnt to 1.4 now and trying to fix his problem I read every single word from you for 2 hours to fully understand this lession since English isn’t my first language.
      "Void" can never return value, so don’t use "void" if you wanna collect something from user (imagine if you gave 60bucks to Horizon Zero Dawn and Playstation refuse by "void"ed giving you the game, what would you think?)
      First you should let C++ know there are numbers: x and y by telling "int x" or "int y"
      And then let user input their own number by giving "cin"
      the "choose" and "choose2" function wrong at "<>", they must be "<<" or >>"
      Since there are 3 functions on ur project, "main" function can not recognise what is x and y, then you should let "main" know by standing int a = choose(or choose2)()
      After the last "<<" of the line 14, you should add more "space" in middle of x and y to make it more comfortable to look at.
      I think ur code should be like that:

      Here is the shorten version

  • My dear c++ Teacher,
    Please let me send you a third example of functions without parameter(s) but with return values and void.
    With regards and friendship.

    • Martin

      #include <stdafx.h>
      #include <iostream>

      int main()
      {
          std::cout << "Enter the current year: \n" << std::endl;
          int CY;
          std::cin >> CY;
          std::cout << "Enter year of birth: \n" << std::endl;
          int YB;
          std::cin >> YB;
          std::cout << "Your age is: " << CY - YB << std::endl;

          outputAge();
          return 0;
      }
        I made this much shorter version of your code. Be carefull not to write long code.

      • My dear c++ Teacher,
        Please let me answer Mr. Martin.
        My dear fellow student,
        Please accept my many thanks for you replied my message and for your suggestion. I written this program as an "example of functions without parameter(s) but with return values and void."
        Also let me advice you following:
        1. Delete "outputAge();".
        2. Delete either "n" or "std::endl" for both do the same job.
        3. Rather delete both for conform with last output "Your age is: 65".
        4. Variable name’s first letter should be small.
        With regards and friendship.

        • phong nguyen

          I think what you had was perfect. You did well-grouping everything into specific functions instead of dumping them all into the main function. If I was a developer working on your code, I would prefer what you had.

      • phong nguyen

        Just for reference, what Georges did is much preferred by many others because he encapsulated everything so it is less prone to errors. Clarity and readability are much more important than the length of code.

  • My dear c++ Teacher,
    Please let me send you a second example of functions.

    //This program get current and birth year and outputs age
    #include <iostream>

    int currYear()
    {
        std::cout << "Enter current year: \n";
        int currYear;
        std::cin >> currYear;
        return currYear;
    }

    int yearOfBirth()
    {
        std::cout << "Enter year of birth: \n";
        int yearOfBirth;
        std::cin >> yearOfBirth;
        return yearOfBirth;
    }

    int age()
    {
        int age;
        age = currYear() - yearOfBirth();
        return age;
    }

    int main()
    {
        std::cout << "Age is: \n" << age() << std::endl;
        return 0;
    }

    With regards and friendship.

  • Felipe

    "which is the where the program starts execution" spelling error that you didn’t catch.

  • My dear c++ Teacher,
    Please let me send you following example of function.

    With regards and friendship.

    • Sadmaan

      your codes are not compiled by codeblocks. please help me out.

      • My dear c++Teacher,
        Please let me reply Mr. Sadmaan.
        Mr. Sadmaan, you can compile and execute it by compiler online
        https://www.tutorialspoint.com/compile_cpp_online.php
        Before you write your year of birth, should click on green surface. About codeblocks ask our dear Teacher.
        With regards and friendship.

  • Mohsen

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

    void thanks()
    {
    std::cout<<"Thank you"<<std::endl;
    }

    int main()
    {
    std::cout<< "Alex"<<std::endl;
    thanks();
    thanks();
    thanks();
    std::cout<< "so much"<<std::endl;
    return 0;
    }

  • My dear c++ Teacher,
    Please let me say true. One year ago I atempted learn c++ from Mr. Bjarne Stroustrup’s book "The C++ Programming Language" 3rd Edition (online), but failed. Now I attempted again and succeed. Apparently thanks to your teaching: text AND answers to my questions. Then, let me sincerelly express my gratitude for it.
    I expect read c++ creator’s book in parallel with your teaching. Do you suggest me that?
    With regards and friendship.

    • Alex

      You’re welcome. If you have the time and the means, I think learning from multiple sources is a good idea. You’ll have more exposure to different ideas and see more examples.

  • My dear c++ Teacher,
    Please let me say my understanging of function.
    It consists of type, name followed by parenthesis "()", an brackets "{}", e.g.

    Parenthesis could include arguments. Brackets could include statements or comments or both.
    Function’s definition is the function itshelf.
    Function’s forward declaration (function’s prototype) is the function when brackets are replaced by semicolon, e.g.

    Function’s call is function’s name with followed parenthesis and, optionally, arguments in them, e.g.

    With regards and friendship.

  • Wyatt

    So return values are good because you can have one function dedicated to figuring out what a certain value should be, then the return statement can send it to the caller function, which can then finish its job.

    main() always must have an integer return value. It returns 0 to the OS to let it know everything’s alright.

    If I understand this correctly, main() and pretty much any other function use return values for different purposes; main() uses it as a status code, but other functions you make use them to send certain values around to figure out what the program should do next. Right?

    Also, I don’t really get what a status code is for, or why it works. When returning the value of 0, is that the program telling the OS “Hey, we’re all done here”? Because wouldn’t that be apparent if there simply was not any code left?

    Also, when you mention that the return statement “typically” returns 0, what would situations be where it would return something other than 0? Would that be something written by the programmer? If so, why? Would it be something that comes about through the program as an error? If so, how?

    • Alex

      You are correct in that you can use return values for different things. Some functions use return values as a status code, to indicate success or failure. Others use return values as a way to pass some calculated or selected value back to the caller. Others pass back nothing. By convention, main always passes back a status code, but the functions you write yourself can pass back any of those options.

      A status code isn’t used to indicate “we’re done” -- it’s used to indicate “we were successful” or “we failed”. Let’s say you wrote a program designed to calculate a square root. However, the user passed in a negative number, so your program can’t run as expected. Instead of doing a “return 0;” (success!) you’d probably want to return some other number (e.g. return 1;) to indicate failure. In most cases, these return codes back to the OS are simply discarded, but they can be useful when you have one program calling another program, and the caller needs to know if the callee succeeded.

      • Wyatt

        I get your first paragraph now, thank you.

        But I’ve got to be misunderstanding something. If you specifically wrote "return 1;" to indicate failure, wouldn’t that mean that you wrote the program with the intention of failure?

        Like, if you wrote a program to do something, & you wrote "return 0;" as a status code, where would a "return 1;" come in? I think I’m missing something. The way I understand it now, I don’t understand why or how you would ever be in a situation to write a failure status code, because that would mean that you are essentially intending for your function to fail. Because a function can only have one return value. You see what I mean?

        Also, I still don’t really get what the status code accomplishes. If the status code reports "success", then great. But if it reports "failure", what would the program do next?

        I’m pretty sure that I’m flatout looking at it wrong, because it doesn’t seem to make any sense.

        I have a feeling I’m not explaining my understanding very well, so please bear with me.

        • Alex

          I understand your confusion, and you’re explaining it well.

          First, let’s restate our constraint: a function can only return a single specific value to the caller.

          However, we’ve already seen cases where the function does not return a constant value. In the getValueFromUser() function in the lesson, the function returns whatever value the user entered, and that value isn’t known until the function actually runs.

          So, if we had a variable (called error) that we could somehow set to 0 on success or 1 on failure, we could return that value of that variable, and the function would return a 0 on success or a 1 on failure, right?

          So the question then becomes, “how do we set that variable to 0 on success or 1 on failure?” We haven’t covered this yet, but the answer is that C++ code can execute code conditionally.

          To use a real-life analogy, if your wife tells you, “if we’re low on bananas, pick up more when you’re at the store”, that’s a conditional command. You only pick up more bananas if you’re low, otherwise you ignore the command.

          C++ has a conditional statement (called an if statement) that allows you to write code that implements this logic: “if there was an error, set this variable to 1, otherwise set this variable to 0”. Then your function can return the value of that variable.

          But it turns out we can simplify and get rid of the variable altogether, by writing code that has the following logic: “if there was an error, return 1, otherwise, return 0”.

          That way, the function still returns only a single value (0 or 1) but which return statement it decides to execute is conditionalized.

          Although it uses some concepts we haven’t covered yet, here’s an example of a real program that you can compile and run illustrating this principle. Run it with a positive and then a negative input and see what happens.

          To summarize: We can use conditional logic to check for errors and have the behavior our function differ depending on whether the condition executes or not. We talk more about if statements in the next chapter.

          • Wyatt

            That clears up a lot, thank you so much! I think the fact that you could actually return multiple return values is what mystified me.

            So now that I understand conditional status codes, I guess my last question is, what does the OS do once it gets a status code? Does it depend on how you wrote the program? What exactly is achieved by the OS knowing that success or failure happened?

            I noticed that, in your square root program, I input a positive, it gives me the square root, then the usual "Press any key to continue…" (return value 1). But with a negative, it goes straight to "Press any key…" (return value 0). But what difference does it make to the OS?

            • Alex

              The OS generally ignores status codes (it only cares when your program has finished executing, so it can clean things up).

              However, the OS makes the status code available (temporarily) to be queried. Most of the time the status code is simply ignored. However, if the program was called by some other program, that other program could query the status code to determine if the program that was called executed succeeded.

              You sometimes see this in C++ code, when one executable calls another executable to accomplish some task. The calling executable can check the status code returned from the called program to see if it was successful or not (and then execute some conditional code based on the result). Otherwise it might have no idea if the called program was successful or not.

              You more often see this used in unix shell scripts, where the script calls some unix executable to perform a task and then checks whether it was successful. If so, it does the next thing the script wants to do. If not, it errors out.

              • Wyatt

                I’d be lying if I said that I completely understood all of that, but I get it well enough now. I suppose I’ll pick up more as I learn more, and eventually I might need to make use of such knowledge.

                Anyway, thank you very much. When learning something, I like to make sure that I understand concepts thoroughly (as well as I’m able) to avoid confusion down the line. So thank you very much for taking time to help me understand!! These tutorials have been very enjoyable.

                • Alex

                  Sure thing. Given your learning style, you’ll probably encounter more questions of the sort. If you feel like something is missing or not answered, read the next tutorial before asking because it may be answered there! If you still can’t find an answer, ask away. Happy learning.

  • Therese McLeod

    Hi,  I’m having difficulties. They’re not working.

    This was new, my complier claims that cout is not a member of std !?!
    and while some of the programs I’ve tried did work, none on this page have so far, is C4droid, with plug ins, okay to use?

    Right, so one finally worked.  (we won’t mention the omission of the ‘namespace std’ which fixed it, although, my compiler seems to have an issue with the word ‘using’) but on others, I know what the code is supposed to do but then the compiler asks for a ‘{‘ or an intitialiser before the ‘void’, but when you add one it comes it with a new error, complaining about the ‘{‘ or ‘int…’.  Help?

    Thanks
    Therese

    • Alex

      C4Droid looks like it’s using GCC, and claims it is almost C++11 compliant, which should be fine. Since this sounds like a product-specific issue, I’d suggest reposting this on the C4droid forums and see if someone more familiar with that software can provide advice on how to resolve.

  • Kiril

    Here is the Code i Made

    #include "stdafx.h"
    #include <iostream>

    int return5()
    {

        //This fuction returns an integer, so a return statement is needed
        return 5; //We are going to return integer value 5 back to the caller of this function

    }

    int evo()
    {

        return 77;

    }

    int main()
    {

        std::cout << return5() << std::endl; //Prints 5
        std::cout << return5() + 2 << std::endl; //Prints 7
        return5();
        std::cout << evo() << std::endl;
        std::cout << evo() + 77 << std::endl;
        
        std::cout << "Well Done" << std::endl;
        std::cout << "Welcome to the NEXTLEVEL" << std::endl;
            int x;
                std::cout << "Give me some numbers: ";
                std::cin >> x;
                std::cout << "The number you give me is: " << x << std::endl;
                std::cout << "Thank you" << std::endl;
                int y;
                std::cout << "Give me another number and try to figure out what i did with it: ";
                std::cin >> y;
                std::cout << "Hmm here is the result after me playing with your number: " << (y + x) * 10 << std::endl;
                std::cout << "So what have i done with the number" << std::endl;

                //Use code that will print the sentence to the console with deley, after 10 seconds
                std::cout << " i added your first number to the second you give me then i multplied the result by 10"

        std::cin.clear();
        std::cin.ignore();
        std::cin.get();

        return 0;
    }

  • Hello Alex
    I have a question
    What is the difference between int and void?

  • My dear c++ Teacher,
    Please let me ask you inspect following program and state whether functions could be used.

    • Alex

      Yes, but it would require some concepts we haven’t talked about yet. Basically, each iteration of variable m could be made a function call, returning a single result (hypoSquared) back to the caller.

      • My dear Teacher,
        Please let me express my sincere gratitude for you replied (my dear dsp Teacher Mr Richard Lyons has stopped replying one year ago) and for your helpful answer. Then I have to wait until we talk about these concepts. I hope will be able to understand that we talk about the required concepts. However I can ask you again about it, when think have learned required concepts.
        I am afraid if now try make each iteration of variable m, a function call, I become confused.
        With regards and friendship.

  • My dear c++ Teacher,
    Please let me report you that four compilers online
    1. http://rextester.com/l/cpp_online_compiler_gcc
    2. https://www.codechef.com/ide
    3. http://cpp.sh/
    4. https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm
    output for program 1g extra credit, 1.
    Only one (http://cpp.sh/) throws warning that is
    “In function ‘int main()’: 9:18: warning: the address of ‘int return5()’ will always evaluate as ‘true’ [-Waddress]”
    My general view of quizzes is that, they are easy.
    With regards and friendship.

  • Georges Theodosiou

    My dear c++ Teacher,
    Please let me express my sincere gratitude for you responded positive my request, and added some quiz questions. Also for, in addition to my request, you rewrote some of the lesson to add some missing points.
    I take into account that reader Mr. Big"B"LuvRRR requested, by March 15, 2016 at 10:17 am, quizzes, but you responded negative.
    Merci bien.
    With regards and friendship.

  • Georges Theodosiou

    My dear c++ Teacher,
    Please let me ask for quiz in this section.
    Merci d’ avance.
    With regards and friendship.

  • Georges Theodosiou

    My dear c++ Teacher,
    Please let me comment, it is strange that, for example, in first and second function call, function is first executed, and then std::cout object, that is before the function. Reasonable is something like this:

    with regards and friendship.

    • Alex

      Consider the following math expression: 2 + 3 * 4. According to the rules of mathematical precedence, multiplication comes before addition, so 3 * 4 is evaluated before 2 is added, even though the 2 is on the left.

      The same thing is happening here. Even though return5() is not the leftmost thing, function calls have a very high precedence, so return(5) is evaluated first to produce a value, and then the rest of the expression evaluates (using that value).

      I talk more about this in lesson 3.1, where we discuss operator precedence.

      • Georges Theodosiou

        My dear c++ Teacher,
        Please let me express my gratitude for your helpfull example from math.
        Bonne année.
        With regards and friendship.

  • My dear c++ Teacher,

    Please let me suggest, in last program to add std::endl;, for,
    http://www.tutorialspoint.com/compile_cpp_online.php
    outputs "foo!sh-4.2$".

    With regards and friendship.

  • My dear c++ Teacher,
    Please let me say that in section "Return values" in text as well in program’s comments, you state (in main(), first function call): "// prints 5", and (in second function call): "// prints 7".
    Actually program prints nothing, for, as you state in the before last paragraph: "You’ll need to comment out this line [std::cout << returnNothing();] of code in order to make your code compile.".
    I think some clarification is needed.
    With regards and friendship.

    • Alex

      Yes, the program won’t compile until you comment out the last line (as noted in the comment). Once you do that, the program will print the results as expected.

      Caveating all of the previous lines to indicate that they won’t produce output until the last line in the program is commented out would be more confusing than not, I think.

      • My dear c++ Teacher,
        Please let me explain that I mean: You could comment, above “include iostream”, something like this

        With regards and friendship.

        • Alex

          Thank you for your concern. However, the specific line that needs to be commented out already has a comment on it:

          That should be sufficient.

          • Georges Theodosiou

            My dear c++ Teacher,
            Please let me comment once more on this issue. In the comment of this line you state:

            I think correct is just the opposite:

            With regards and friendship.

            • Alex

              No.

              “Commenting out” is a standard/common phrase indicating the use of comments to remove one or more lines of code from being compiled. You’re using comments to take the code OUT of compilation.

              If you say “Comment in”, nobody will know what you are talking about, even though you technically ARE adding comment tags in to do the commenting out. 🙂

              • Georges Theodosiou

                My dear c++ Teacher,

                Please accept my thanks for you replied and for your explaining answer. By "comment out" I was meaning what you say "uncomment". I regarded them synonyms.

                With regards and friendship.

  • My dear c++ Teacher,
    Please let me be complainer (as usual), saying that you use functions names same to job they do. It confuses me! You could use other names, for example instead of "returnNothing()", "makingLove()"!
    With regards and friendship.

    • Alex

      For trivial examples like these, I’m using the function names as a way to point out some property about the function that I want you to focus on. For example, returnNothing() has a void return value. It could be named anything else, but no other name is likely to draw quite as much attention to this property.

      • My dear c++ Teacher,
        Please let me say that I mean:
        As long I understand english (am Greek), "return nothing" is order (command) to somebody to return nothing. But "returner nothing" means, somebody who returns nothing, that is the case with function in question. So appropriate name is returnerNothing(), also returner5().
        With regards and friendship.

        • Alex

          It would probably be more proper to name the function “returnsNothing”, since we’re talking about the present and the function is acting as a third person singular verb. But with function names, return is often used instead of returns because return is a keyword used to indicate a specific return value.

          “Returner nothing” would be improper English -- you could say “ReturnerOfNothing” though.

  • Phillip OBrien

    Why does the void function "returnNothing" even exist and why do we have to make a call to it?

    • Alex

      As written, function returnNothing() was useless. I was just using it to illustrate how return values work, and what a void return value is. In practice, there would be no reason to call it.

      However, since I can see how having a function that literally does nothing might be confusing, I’ve added a trivial output statement to it.

  • SilentStrikerTH

    So I made this program to test the things I’ve learned and I am getting a weird number at the end and I’m not sure why.

    [
    #include <iostream>

    int addition()
    {

        int x;
        int y;
        int z;
        std::cout << "Enter Your First Number: ";
        std::cin  >> x;
        std::cout << "Enter Your Second Number: ";
        std::cin  >> y;
        z = x + y;
        std::cout << x << " + " << y << " = " << z << std::endl;
    }

    int main()
    {

        std::cout << "Welcome To The Addition Calculator!" << std::endl;
        std::cout << addition() << std::endl;
        return 0;
    }
    ]

    When I build and run I get the input:

    Welcome To The Addition Calculator
    Enter Your First Number: 6
    Enter Your Second Number: 9
    6 + 9 = 15
    6295968

    That 6295968 is the number I am not sure where is coming from, can anyone tell me why its there?

    • Alex

      Your program is malformed (I’m surprised it compiles). You’ve declared function addition() as returning an integer, but the function doesn’t actually return a value. You print the return value in main(). I presume since you didn’t return a value, the program is returning a garbage value (which in that case just happened to be 6295968).

  • Logan39

    Hi I just started the first program above. "This program produces the following output:
    Starting main()
    In doPrint()
    Ending main()"

    I understand it represents a Call, but how do you make this a more useful example? If you look at the code, all it really does, is sends the code from the bottom to jump to the top one in the middle then back to the last line to complete. For example, could you add a call that will only activate this sequence of jump if the user presses a button or provides a rogue variable that triggers it? Would that not provide a more practical example to see how the whole process could work in real life? Would it be too complicated at this stage or am I getting way ahead of myself?

    • Alex

      I agree, the example isn’t very useful, but it’s meant to illustrate a principle, not define a useful program. Future lessons introduce other bits of functionality that we can start leveraging to build programs that ARE actually useful. We just have to start somewhere, and somewhere is here. 🙂

  • Emiliano Felix

    Hello Alex… I don’t really understand the meaning of the return type void. Why or when would you use it?

  • Aparna

    Hi Alex, Can you please explain the situations where other functions are called before main() ?

    • Alex

      Having any function execute before main() is uncommon, but it is possible. When your program is executed, the program will do some setup work to ensure any global variables are allocated and ready to go before main() starts execution. When these global variables are created, a function can be called to provide an initialization value.

      For example

      We cover global variables in chapter 4.

  • Herman

    Why won’t this compile successfully?

    • Alex

      When you compile this, the compiler should tell you why it won’t compile:
      main.cpp(36): error C2062: type ‘int’ unexpected
      main.cpp(37): error C2062: type ‘int’ unexpected

      That’s these lines:

      The problem is the second use of int shouldn’t be there. It should just be:

  • Juan

    This is by far the best tutorial I have came across. Everything makes so much more sense now because of the way you explain it.
    Thanks very much!

  • Zackary Ramirez

    returnNothing();
        return5();

    These statements are in the code however it seems the code works completely fine without them. What is the purpose if there is any? Just a novice trying to get a good foundation for the concepts

    • Alex

      The purpose is to demonstrate that you can call functions that do not return values (in the case of returnNothing()) or that you can ignore the return value of a function if you want (in the case of return5()).

      Since neither of these functions does anything else (for simplicity), the calls end up being useless. But you can easily imagine the case where these functions have other purposes (printing something to the screen) -- and in that case, if you removed them, you’d change the way the program functioned.

  • Mufty

    Please check for me if is correct. cos i don’t know why my code don’t add the numbers as i want it to do. is there any help.i wanted to add x + y. please can anyone try to help me out. I am a Beginner

    #include <iostream>

    void DoPrint()
    {
        using namespace std;

        cout << " Please enter a number " << endl;

        int x;

        cin >> x;

        cout << " You entered " << x << endl;

        cout << " Enter a number again " << endl;

        int y;

        cin >> y;

        cout << " You entered " << y << endl;

        cout << x + y  << endl;
    }
    int main()
    {
        using namespace std;

        cout << " Hey thanks for coming " << endl;

        DoPrint();

        cout << " Like to see you next time " << endl;

        return 0;
    }

  • Imnoob

    #include <iostream>
    int multiply()
    {
    std::cout<<"Enter the no"<<std::endl;
    int a,b,c,d;
    std::cin>>a>>b>>c>>d;
    x=a*b;
    int x;
    std::cout<<"1st pair ="<<x<<std::endl;
    y=c*d;
    int y;
    std::cout<<"2nd pair ="<<y<<std::endl;
    return x,y;
    }
    int sum()
    {multiply();
    int w=multiply();
    int m=multiply();
    int sum;
    sum=w+m;
    std::cout<<"sum="<<sum<<std::endl;
    }
    int main()
    { std::cout<<"this program will first multiply no in pairs,then prints its sum"<<std::endl;
    sum();
    return 0;
    }

    program gives this error :
    prog.cpp: In function ‘int multiply()’:
    prog.cpp:7:1: error: ‘x’ was not declared in this scope
    x=a*b;
    ^
    prog.cpp:10:1: error: ‘y’ was not declared in this scope
    y=c*d;
    ^

    and one more Q can we call main function from any other function like if we want to add two no we declare each and everything in main but call it from some other function to execute it(ps i tried but failed, as execution starts from main and if we define everything there it will simply show the output this is where i got busted)

    • Alex

      You use x and y before you define them. If you move your definition for x and y up one line each, this should be fine.
      Note that a function can only return one value -- return x,y does not do what you’re expecting.

      You can call main from another function, but I don’t think I’ve ever seen a case where you’d want to do this.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter