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 function, we use a return statement to indicate the specific value being returned to the caller.

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 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 the return value is discarded.

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 a 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

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

  • Eric

    For some reason, some of your code won’t work if I enter it in manually without the notes. I’m using Code::Blocks on xubuntu. It works fine if I copy/paste your code, but it doesn’t like my hand copied version. What am I missing?

    I figured it out, I forgot the space between “return” and “5” in the first set of {brackets}.

  • Chris

    You said  "it must return a value of that type (using a return " but could you use return function but you don’t return anything back to the caller or will it give a compile error

  • Hardik kalra

    Hey Alex ! Can U Tell Me Why Do Nested Functions not work in C++? Plz Tell Me The Reason. I want to know it !

    • Alex

      I’m not sure why they weren’t added to the language. I do know that they were considered (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0295.pdf) but it’s unclear why they weren’t included.

  • Ahtazaz Khan

    Hi Alex,i have a question about return value.We normally write ‘return 0;’ at the end of Main function.
    How to check which value is return to the Main function by the program? Whether it is 0 or something else … ???

    • Alex

      > How to check which value is return to the Main function by the program?

      You don’t want to check which value is returned to the main function, you want to check which value is returned to the operating system by the main function.

      Your IDE probably contains some way to display this. In Visual Studio, if you run your program in debug mode using “start debugging”, it’ll print something like this into the output window:

      The program ‘[13864] ConsoleApplication1.exe’ has exited with code 1 (0x1).

      • Ahtazaz Khan

        In this statement "The program ‘[13864] ConsoleApplication1.exe’ has exited with code 1 (0x1)", 1 (0*1) is the value that is returned by the main function to the operating system…?? or something else…? Actually i didn’t get your answer… Thanks Alex.

        • Alex

          That’s the value returned by the main function to the operating system. In this case, the program returned 1 instead of 0.

          If you want to see the value returned by an internal function to another internal function, you should be able to inspect that in your debugger.

  • Akshay

    If void doesn’t return anything, how in this code it returned In doPrint() to the main function?

    • Alex

      A void function doesn’t return a _value_ back to main, but the path of execution still returns to main.

      • Akshay

        I am unable to understand what are you trying to tell, please elaborate it. In the above code it returned In doPrint() output but in the below code the output doesn’t contain Hi . Why is that difference though the code looks same?

        • Alex

          The output in your quoted code should contain “Hi”. main() calls returnNothing(), which prints “Hi”. Then returnNothing() finishes and returns back to main(), where execution continues and the program ends.

    • Ram

      Inside "main()" you are just making a call to the user defined function "doPrint()"
      The "doPrint()" does not actually return a value, rather it prints "IndoPrint()" and returns to "main()" to execute next set of actions.

  • Stelios

    if void does not return a value then how in your examples does the program output A and B
    i am confused

    • Alex

      The function printA() prints the letter A and then returns no value back to the caller.

      printB() works similarly, except it prints B instead of A.

  • Martin

    What other source do you recommend me to learn C++ from, or where was your most influential step that cleansed and enhanced your C++ skills?
    Best regards, Martin.

  • My dear c++ Teacher,
    Please let me say, in programs of this lesson you suggest for Visual Studio:
    #include <stdafx.h>
    I have a comment on it: VS 2017 although runs fine with it, it is not including in drop down menu. It is including
    #include "stdafx.h"
    With regards and friendship.

  • Noah

    I’m pretty sure I understand calling. When main receives something that is defined elsewhere, the processor calls that function to define what main is trying to do and describes the variables being used in main. However, I’m lost on what voids are. A buddy of mine told me they return nothing to c, but I’m confused still. Is void just a function to define something behind the scenes of the actual function happening?

    • Alex

      You seem like you’re close, but I’m not sure you quite have it. When a function is called from main, the program puts a bookmark after the function call being made, jumps to the function being called, executes it, and then returns back to main (at the point of the bookmark) at continues executing. The only thing main receives is the return value from the called function, if there is one. void is used to indicate that the function does not return a value back to the caller.

      • Noah

        So what then is the point of a void if it isn’t going to output a value to main? I thoroughly believe there is a reason, such is the reason of a void being taught this early. I’m just not quite grasping what you would use a non-return function for. Does Main give the integer to the void function, which the void function then uses to calculate the values of the integers given by main?

        ^Update:
        From my brushing up on knowledge of what return is and what void does, my basic understanding is this. Return (Value) says if it was run successfully or not. A void returns nothing to the processor, therefore does not need a return function. voids only exist to plug variable integers in and use them in a function, and send it back to main. Tell me if I’m right, wrong, or going the opposite direction in my understanding. I think I’m closer than I was

        • Alex

          It sounds like you’re still close but not quite there.

          Two things:
          * The main() function must return an integer to the operating system, which indicates whether the application was run successfully (0 = success, non-zero = failure).
          * All other functions can choose whether they want to return a value back to the caller or not, and what the meaning of this return value is. Void is used to indicate no return value back to the caller.

          So, for example, a function that does nothing but print something would not need to return anything back to the caller (what would it return?). This function would use the void keyword as the return value, indicating no return value. A function that calculates a value based on some other values would probably want to return this calculated value back to the caller. In this case, a return value would be used.

  • Alice

    getValueFromUser, returnNothing, doPrint.
    Why do they always start with a small letter? Does it matter what the word(called function?) is? I keep getting the same result even if I used one letter(I know it may not be a good idea but I wanted to see the difference).

  • Claudio

    I know this is very simple, and that i don’t need a function to do this, but i was just trying some stuff while i was learning.

    i wanted to know why if a call suma() doesn’t give me the number that should (if I enter number 2 , 3 and 5 at the end it prints a random 6 or 8 digits number, but when i put this

    it prints 10)

    • Alex

      The problem here is that the a, b, and c inside main are separate from the a, b, and c inside suma() (despite using the same names). The values the user inputs into main’s a, b, and c aren’t transferred to the a, b, and c inside suma().

      If you want those values to transfer (and given the structure of your program, you do), you should pass a, b, and c as arguments to suma() instead of having suma() define a, b, and c inside the function body. We cover how to do that in the next lesson.

      • Claudio

        thanks! I wask kinda short of time, so I read this one and ask that, and now I’m going to keep going, sorry about that.

        By the way… this page is just great! and you be solving this problems after all this years… WOW you’re awesome.

  • 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.

  • 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.

  • Antonio

    So I’m I have this program working and does what it needs to do, however it doesnt stay open after putting in the 2nd integer. The second issue is I want it to "return" back to functionmain() once 2 integers are entered, and start the sequence again until the user decides to exit the program.

    For the first issue I tried putting

    right before the return 0; in int functionmain() and it seems to work, allowing the program to stay open after putting in two integers.
    So I guess the only issue is having the program "restart" at the int functionmain() to be executed again.

    Main code>>>>>>

  • Witson

    Why main function is alwyas last? Is there any particular reason for that?

    • Alex

      Yep. C++ compiles files from top to bottom. So if main() is going to call any other functions, those functions need to be listed before main(), otherwise the compiler won’t know that they exist.

      I cover ways to work around this in later lessons in this chapter.

  • abhimanyu

    hey guys check out my code
    #include <iostream>
    using namespace std;

    int print()
    {
    int x;
    cout<<"please type a number:";
    cin>>x;
    return x;
    }

    int main()
    {
    int a=print();
    int b=print();
    int c=print();
    int d=print();
    int e=print();
    int percentage=(a+b+c+d+e)*100/500;
    cout<<"your % is:"<<percentage<<endl;
    cout<<"and your cgpa is:"<<percentage/9.5<<endl;
    if(percentage>70)
    {
    cout<<"your score is very good"<<endl;
    };
    if(percentage<70){
    cout<<"your score is not that good"<<endl;
    };
    if(a<70)
    {cout<<"need to work on your first subject"<<endl;
    };
    if(b<70)
    {
    cout<<"need to work hard on your second subject"<<endl;
    };
    if(c<70)
    {
    cout<<"you need to work hard on your third subject"<<endl;

    };
    if(d<70)
    {
    cout<<"you need to work hard on your forth subject"<<endl;
    };
    if(e<70)
    {
    cout<<"you need to work hard on your fifth subject"<<endl;
    };

    return 0;

    }

  • jeff

    can’t believe i found this website in 2016,good tutorials for learning c++ programming

  • Laatokka

    Hello,
    My program build correctly, but once it gets into my second function, it fails.

    It clearly is not returning 0. The number is -1073741676.

    • Alex

      Yes, because your local variables (main’s x, y, and z) are shadowing the global variables of the same name within function main().

      You should be passing x, y, and z as parameters to CalculateNumbers(), and CalculateNumbers() should be returning b as a return value.

  • Russell

    I’m glad I found this site, my professor sucks and doesn’t explain that well so we either copy what’s on the screen(without understanding what it is) or do nothing.

    Tnx very much Alex!

  • Michael

    So far, as a complete novice, I seem to be following your tutorial sufficiently.  I’m having a problem with Visual Studio 2015, however, in that once I compile, build, and run the program (say HelloWorld.exe), my computer seems to keep it running in the background, effectively giving me the fatal error LNK1168 every time I try and make changes (to experiment and verify my understanding).  Last time, in order to make changes, I had to restart the computer in order to delete the existing project and then start over from scratch.  I have to guess that I’m doing something wrong, but an hour of googling hasn’t brought me closer to understanding the issue.

    • Alex

      With visual studio, once your programs run, they may be pausing at the end, waiting for you to hit a key to close them. Try making sure the console window that pops up when you run your program is focused, and then hit enter.

      If that doesn’t work, I have no idea. 🙂

      • Michael

        Okay, well, I figured it out.  I had forgotten to disable my AV before running the program, and for some reason that caused the program to be kept open.  I just need to remember to disable my AV BEFORE running the program if I don’t want to have to restart my computer to rebuild it.

  • why do methods need to be declared before the main() method if I want to call them? If im not mistaken Java can call methods/functions that have been declared after the main method, just wondering what makes cpp different

    • Alex

      Simply because C++ is older. This was originally done for efficiency, so that the compiler doesn’t have to do two passes through each file.

      Because Java is newer, they were able to address some annoyances.

  • The_Spankles

    I have a program, that I am just testing with.
    I want the user to be able to enter a number, and it to output the word "word" that many times. however it doesn’t know what the values are in the call. even though I create the values in the main. here is what I have.

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

    int forever()
        {
            std::cout << "Word ";
            y=y + 1;
            if (x>y)
            {
                forever()
            }
            if (y == x)
            {
                std::cout << "All Done. ";
            }

        }
        //-------------------------------------
        int main()
    {
        std::cout << " How Many Times Do You Want Me To Say What’s UP? ";
        int x;
        int y;
        y = 0;
        std::cin >> x;
        forever()

    }

    • Alex

      Having function forever() call itself is called recursion. You could make this work by passing in variables x and y as function parameters, so that forever() can determine when to stop calling itself.

      However, in most cases (including this one), recursion isn’t the best way to make a program do something more than once. Instead, you’ll want to use iteration (also called looping). We cover that in chapter 5!

    • Brian

  • Anna

    My dad says that I cant download stuff into his computer ( I’m 11 ) so I’ve used compilers online.
    but I’ve found that whenever I try to call on a function it gives me an error. am I not understanding something!?

    int main()
    {
        std::cout<<"Hello"<<std::endl;
        end();
        return 0;
    }

    void end()
    {
        std::cout<<"Goodbye"<<std::endl;
    }

  • kaylee

    Hello! 🙂
    I am on lesson 1.4 and I’m starting to crumble when it comes to understanding these things.
    Your tutorials are extremely thorough but since there are so many complex rules, I have difficulties grasping them because I need to apply them to something!! If that even makes any sense?

    I have Visual Studios and I have made 4 projects to better my understanding of how things work such as user inputs or me outputting text "Hello World!" But after integers and function calls were brought into the equation (no pun intended), I’m having troubles really grasping them because I don’t really know how to apply it to anything.

    I hope that makes a little sense? I’ve spent hours and hours and hours reading and applying but now I’m stuck, I’m afraid that I’ll get discouraged by this and lose interest way too early in the game. 🙁 This is a combination of things I love, Math..Gaming..Satisfaction.. I don’t want to give up so soon as I’m 16 and desperately want Software Engineering to be my career choice.

    PLEEEAASE ADVISE!!!! 🙁 And thank you so much for taking time to create FREE tutorials that are so profound! If you do have time, the encouragement and advice would be so useful. Thank you so much again. 🙂

    • Alex

      Hi Kaylee,

      It’s hard to advise you because your concern is so general. If you have specific questions, I can answer them. Otherwise, I’d advise playing with the examples (e.g. changing lines to see what the effects are).

  • pirate

    Hi Alex, this is a simple program that i just wrote, and it does not seem to compile.
    What’s wrong with this program?

    • Alex

      This program has quite a few errors.

      First, function firstNumber and secondNumber say they return ints, but the return statement is returning a double.
      Second, the first and second lines in main() calls firstNumber() and secondNumber() but discard the result.
      Third, in your statements at the bottom of main, you’re trying to add firstNumber + secondNumber, but those are the names of the functions. How do you add function names? It doesn’t make sense. You either need to add the result of the function calls (e.g. firstNumber() + secondNumber()) or you need to replace those with variable names.

      Personally, I think you should assign the result of firstNumber() and secondNumber() each to variables at the top of main, and then use those values for your arithmetic.

  • Mithun

    Alex..
    You are doing a great job. Though I am having 5 years of experience in C++, still I am getting new things in your tutorial.

    I appreciate your responses to small queries which is like teaching ABCD..to a child.

    Great job…and Hats off Dude..
    Thanks a lot..

  • Nyap

    So basically a function call is a statement telling the program to execute a different function?

  • Zuy

    Hi Alex,
    Thank you so much for the amazing guide and even though I’m very new to programming, I’ve picked up quite a bit from your previous lessons and surely enjoyed myself as well. I just want to clarify a few things:
    -What do you mean by "caller"? Is it referring to the main function?
    -I’m not too sure what "return" does and how the number beside it affects the function?

    • Alex

      Consider a telephone: the caller is the person who picks up the phone and dials, and the callee (or called) is the person who got dialed.

      In programming, the caller is the function that causes the called function to execute. In the top example above, the caller is main(), and the called function is doPrint().

      A return value is used to allow the called function to pass a value back to the function that called it. So when we say “return 5”, that means the called function is returning the integer value 5 back to whichever function called it (in the example above, main()). Main is then free to do whatever it wants with that value, including ignoring it.

  • pirate

    Hi Alex, i have a question for u…

    I dont get what is the use of returning values to the caller (the operating system) after writhing every program.
    I mean lets take the hello world program as an example… I tried building it without the return statement at the end of the function and it still works perfect

    (I am still a newbie )

    • Alex

      This return value from main 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.

      Some compilers will let you omit the return statement from main() (in that case, they implicitly return 0). This is technically illegal, so you shouldn’t rely on it.

  • sharaf

    In subheading RETURNING TO VALUES the program where we used returNothing() and return5() function when i omitted line 20 &  21 program compiled properly and when i read the explaination i didnt understood the part where u made this sentence In the fourth function call, return5() is executed. The value 5 is returned to main(), but main() does nothing with the return value so the return value is discarded.
    i here mean what main() should do with the value.
    and please explain the line 20 and 21

    • Alex

      The function return5() only does one thing: passes the value 5 back to the caller (in this case, that’s function main()) via the return value. Since main does not do anything with this return value (assign it to a variable, print it to the console, use it in an expression, etc…) it’s simply thrown away.

  • Aaron

    I use code blocks and when i start it up i get the screen you get when you first start up codeblocks and then i try to start a new project and the entire screen (except the bar at the top that says
    file edit etc…) i had an issue before this where the bar didnt show up at the side of the screen (where it shows you all your projects and things) please help i cant code without it!

  • Gravy Butt

    I’m still confused on return values and their purpose. When a return value is executed, I understand that it returns that value to the caller, but what HAPPENS to the number after that? Where does it go? Also, I can’t really see the use of returns either, could you give me an example, where you might need to use one, and where they are helpful?

    • Alex

      After a value is returned from a function to the caller, it is the caller’s responsibility to decide what to do with it. The caller can decide to ignore the value, in which case it is discarded, store the value in a variable, use it in an expression, or pass it directly as an argument to another function.

      Return values are used all the time. For example, let’s say you have a list of names, and you want to know if the name “Alex” is on the list or not. That’s a great job for a function. But the function needs some way to tell the caller whether the name was found or not, right? It can use the return value for this.

      The getValueFromUser() function in the example above is another common pattern -- we need to ask the user for input multiple times. But how would we get whatever the user typed back to the caller without a return value? (In actuality, there are other ways, but the return value is the easiest).

  • Rishi

    as we know return function gives value back to the function e.g.
    int somefn()
    {
        //your code
        return 5;
    }
    this will return the value 5 to somefn()

    but when we write return value as zaro to main function so could it gives back some integer value other than 10. e.g.

    int main()
    {
       std::cout << "Enter number: " ;
       int x;
       std::cout << "You Entered: " << x << std::endl;
       return 0;
    }
    This prog should return value 0 to main and what we get as output is the value we entered for x insted of 0
    plz explain
    i am confused

    • Alex

      > as we know return function gives value back to the function e.g.

      No. A function’s return value gives the value back to the _caller_ of the function, not the function itself!

      When main() returns 0, it’s returning that value to the operating system, who is the caller of main().

      • sharaf

        me too is confused with return in the above program which rishi gave.. there is no function call .. and what do you mean by "A function’s return value gives the value back to the _caller_ of the function, not the function itself!"
        please explain in beginners language coz i am new!

        • Alex

          There is a function call: function main() is called by the operating system to start the program, and the return value of 0 is returned back to the operating system.

  • Ashwin Sewambar

    I got a bit of a boring comment, the definition of nesting is given in this post, but the word nesting actually has already been used earlier in the section on ‘comments’ (and therefore should actually be given there). I know this is the worst whining ever, but…well. Anyway.

  • rahimi

    i have a question

    if a student has 5 subject each subject total marks are 100, how to find the obtaind marks of each subject,total marks and percentage out of 100
    also if a student got 90 marks on grad A,85,grd b ,80 grade c
    if student got 49 marks fail.

  • bharadwaj_pro

    Hi
    Why there is no std::endl after the function?
    For example

    is correct.
    But not

    • Alex

      I’m not sure why I didn’t add std::endl originally. I updated the example, because I think it makes more sense for each output to be on a separate line.

  • Luke Ellison

    I have a very basic question as I am brand new to this and just trying to figure out what is going on. I am using Code::Blocks. I’m trying to retype the text you have into my program exactly how you have it, but I notice you have a lot of typing all on a single line number. Like the first example has 7 rows of text corresponding to line #1. I don’t know how to spread more information among one "line" or if it even matters. Other times you have complete rows empty of text within a line number which I can’t figure out how to do either. I end up with 20+ lines when you only have 4 or 5.

    • Alex

      That sounds like a glitch with the line numbering code. I’ve seen that happen occasionally. Usually refreshing the page solves it for me.

      Line numbering is just a convenience (so we can talk about particular lines of code, as well as so the compiler can indicate which line an error was encountered on).

      If your line numbers are different, it shouldn’t matter much.

      • Luke Ellison

        I’m back here today and every line has a number now in your examples. I suspected it didn’t make much difference but I was confused about how or why it was presented the way it was. Thanks for the response!

  • Amin

    In the name of God
    hi alex,
    i write this code for my test of input and output order of
    function arguments , but in running , its result is not order that i my suggest . i suggest first show readNum1 and Then readNum2 but its print first readNum2 and then readNum1 value .
    I confused
    thanks for your consideration
    Hope to God
    --

    --
    Please enter a number two :
    2
    Please enter a number one :
    1
    12
    Press any key to continue . . .

    • Alex

      C++ does not guarantee the order in which function parameters will be evaluated. Thus, in the line pri (readNum1(),readNum2());, it’s not determinate whether readNum1() or readNum2() will be called first.

      You can restructure this so the ordering is explicit:

      • Big"B"LuvRRR

        Some observations:

        1) Seems like the second argument is consistently worked on first!! In my Code::Blocks, anyway…why is this?? (To insure the correct order, I simply switch the arguments around…looks stupid, I know, but it seems to “work”….)
        2) Your solution, Alex, seems to merely replace one set of arguments with another set -- why should this in itself work???  IOW, how’s your solution actually more "explicit," as you say…please "unpack" the reasoning here for me; thanks!!!

        • Big"B"LuvRRR

          Clarification:

          1) I just did

          and

          and that seems to insure the desired order!  But why???

          2) How is making the arguments variables (that in turn have the functions as their values) somehow more "explicit" to the compiler instead of simply having those functions as arguments?????

          Thanks.

          • Alex

            As I noted, C++ does not tell compilers whether to evaluate function parameters from left to right or right to left, so different compilers may do things differently. Some may go left to right, some may go right to left. Whichever way your compiler does it, it will be consistent in and of itself.

            The problem with

            Is that it’s not clear whether readNum1() or readNum2() will be evaluated first.

            My solution disambiguates the order of resolution by using multiple statements, each of which executes sequentially:

            Your solution in #1 above may work for _your_ compiler (because your compiler apparently evaluates right to left), but it may not work for other compilers that evaluate in a different order.

  • Aryan

    Hello. I have a question. I haven’t yet setup my own C++ IDE. I use cpp.sh instead. I got a issue, whenever I run this code, it starts for a second, and the closes. Doesnt show the Enter a integer or anything. I this a website side problem? I used cyber cafe to learn C++ and they wont allow me to add C++ on their PC so i use that website.

  • moese

    i,m using visual studios 2015 I.D.E. why should i use a return 0 when my int main is working without it or why is my int main working without it? i ran programs with and without compiler & syntax errors and with and without return statements in the int main definitions and the "return 0 statement didn,t have an impact on correct definitions or on error messsages on definitions w/ syntax errors. Is it my compiler or am i missing the point?

    • Alex

      Your compiler is allowing you to write invalid C++ code for the sake of convenience. I can’t speak to why Microsoft thought this was a good idea. If you try to compile a program that doesn’t have a return statement in main on another compiler, it will probably give an error.

  • Dick

    Hi, I made this to see if a function could call another function.  It worked, but only if I coded them in order, if not there was a Build error.
    If I placed int testcall2() first it caused an error.
    I also wanted to test if you could create and set a variable outside of the main code (), that would make the variable global, right?

    Great Web Site!

    Any comments?

    • Alex

      Good use of experimentation to answer questions.

      Yes, a variable declared outside of any function is a global variable. We discuss those in chapter 4.

      We also talk about how to make it so you can do your functions in any order later in this chapter.

  • Hamed

    Hi, You told that for Visual Studio we need to add

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

    I use Visual Studio 2015 But, its opposite and when I add that line get error. What is the problem?

  • what is difference between endl and \n ,
    why we need to declare user defined function before main function…..
    if we declare after the main function then it will give error ,why?

  • #include<iostream>
    using namespace std;
    void main()
    {
    cout<<"Hello World";
    }

    tell me that why its give error that "main must return int ."
    in c language its do not give any error,,,why???

    • Alex

      Because this is not C. 🙂 In C++, it is specified that function main() must return an int. Some compilers allow you to bend this rule anyway, but technically it’s illegal.

  • hi i have problem with all functions in c++..
    would any one please help me !!!!

  • yash

    #include <iostream>
    int main()
    {
    using namespace std;
    cout<<"Hi Alex.<<endl;
    cout<<"Great tutorial."<<"\n"<<"I want to participate in programming competitions. Which website is best.";
    cin.get();
    return 0;
    }

  • Brandon

    Hi! I have a little problem. I just wrote a little something and it isnt doint what i want. Im using VS 2015 and compiling works, but when i run the program it skips the "userfirstname" and goes from the age to the second name. My cout in main then puts a randome number to userfirst name (as you showed us). Frankly it just skipps "userfirstname". Any solution?
    PS: In VS the main cout does not use 2 lines, just one.
    Cheers Brandon

    • Alex

      There’s a few issues here. The main issue is that you’ve declared y and z to be of type int, but you’re asking the user to put a string in it. Integer variables can only hold non-decimal numbers. We cover how to handle strings (such as people’s names) later in the tutorials, since they’re a little more complex in C++.

      Second:

      Doesn’t do anything. These are just function names, not function calls.

  • Hi Alex, Our lord and savior, son of our beloved c++ gods.
    I have come to thank you for your benevolent actions of the tutorials
    Will you come and save us from humanity.
    The world is in deep danger and we need your enlightenment.
    Please respond As soon ASAP as possible.

    -Ayy Lmao

  • Mickey

    Ok so its been a little bit since I’ve programmed and I’m trying to get back into it.
    My output is
    Hello World!
    Enter a Number

    I do that, and the window closes on me. I don’t understand why it’s not displaying "The number you entered was "

    • Alex

      Replace your cin.ignore line with all three of these and see if that fixes your issue:

  • Freffy

    I cannot figure out how to transfer text between functions, I can only get numbers to work.

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

    int fuzz()
    {
        using namespace std;
        cout << "enter text here" << endl;
        int x;
        cin >> x;
        return x;
    }

    int main()
    {
        fuzz();
        std::cout << "you typed" << fuzz() << std::endl;

        return 0;
    }

  • Thomas Keith

    Alex,

    Your reply to Adam above is:
    " If a variable is declared in one function, other functions won’t even know it exists unless you pass it as a parameter.
    The reason you are getting an error is because x is declared in main(), so loop() is unaware of it’s existence."

    Will a variable be global if declared right after your #include statements?  If so, isn’t it right that its value would change according to any function that affected it?  Seems like that could either be a blessing or a real mess, depending on how you used that variable.

    • Alex

      Yes, you are correct. A variable declared outside of a function is a global variable, and that variable can be changed by any function. In most cases, it ends up being a real mess. I talk about global variables further in chapter 4.

  • Thomas Keith

    Alex,

    First, thanks first for the tutorials.

    In quiz question 5, I tried to declare and initiate my variable in this way:

    but got this error:
    error C2440: ‘initializing’: cannot convert from ‘std::basic_istream<char,std::char_traits<char>>’ to ‘int’

    It seems so much more elegant to declare and initialize a variable in a single line.  Is there no way to do this short of writing a function to do it?  Some scripting languages let you do this, such as AutoIt and I think .vbs allows it as well.  Example:
    $x = InputBox (parameters needed by the scripting language).

    Again, thanks for the tutorials.

  • Sharjeel Safdar

    Hi! Mr. Alex, in this example of yours, there is no return statement at the end of the main() function body. The main() function itself is not returning any value to the operating system: but this programme still worked when I compiled it in my IDE, Visual Studio 2013 (only I had to comment out the line 24). Why is this so?

    Also thumbs up for your excellent tutorials.
    Waiting eagerly for your reply.
    Thanking you in anticipation.

    • Alex

      Oops, the lack of a return value from main() was a mistake.

      Some compilers (such as Visual Studio) will assume you meant to return 0 if you do not explicitly specify a return value from main(). This does not follow the C++ standard, but is sometimes useful.

      • Marc

        Actually, in C++ it’s legal to omit the return statement from the main function. If you do so, the main function will implicitly return 0. See Section 3.6.1 of the C++14 standard. This rule only applies to main(); for all other non-void functions you must expressly return a value.

  • Hridayesh Sharma

    Thanks alex i have got it
    these are nice tutorials

  • Hridayesh Sharma

    #include <iostream>

    // void means the function does not return a value to the caller
    void returnNothing()
    {
        // This function does not return a value so no return statement is needed
    }

    // int means the function returns an integer value to the caller
    int return5()
    {
        return 5; // this function returns an integer, so a return statement is needed
    }

    int main()
    {
        std::cout << return5(); // prints 5
        std::cout << return5() + 2; // prints 7

        returnNothing(); // okay: function returnNothing() is called, no value is returned
        return5(); // okay: function return5() is called, return value is discarded

        std::cout << returnNothing(); // This line will not compile.  You’ll need to comment it out to continue.

    }
    CAN YOU EXPLAIN THESE LINES REGARDING THIS PROGRAM

    "In the fourth function call, return5() is executed. The value 5 is returned to main(), but main() does nothing with the return value so the return value is discarded.

    In the fifth function call, 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"

    • Alex

      return5() is a function that returns an integer value (in this case, 5) to the caller. When main calls return5(), the function returns the value 5 back to main. But main doesn’t do anything with it (e.g. assign it to a variable, print it, etc…). Since it’s not used, the return value is discarded.

      returnNothing() does not return a value to the caller. std::cout needs data to print. Since returnNothing() doesn’t return anything, main doesn’t have a value to send to std::cout. The compiler will notice this and throw an error.

      What specifically are you finding confusing?

  • Osheen

    why is it so necessary to use std. My code even works without it. Infact I never used or heard it before.

    • Alex

      All of the functionality in the standard library has been moved inside the std namespace to avoid naming conflicts with user-defined identifiers. The best way to access that functionality is via the std:: prefix.

      If your compiler doesn’t give you errors when you try to access standard library functionality without referencing the std namespace somehow, you must have a really old compiler. You should probably update.

  • Drew

    I am sure you have answered this question before, but I could not find it in the comments. How come the main function has to always be below any other functions. When is say "below", I mean physically on the lines below the other functions. I attempted to build a code with the main function above a void and or int function, but it failed to build. What is the reason behind this?

    Thank you for these fantastic tutorials.

    • Alex

      The main() function actually doesn’t need to be below the other functions, but for convenience it normally is.

      When the compiler compiles your program, it does so from the top of the file to the bottom -- and it only scans each file once. Therefore, if you make a function call in main() but haven’t defined the function being called yet (because the definition is below main()), the compiler will complain.

      There are two ways around this:
      * Put main() at the bottom so all functions are defined above it, to ensure the compiler encounters their definitions before compiling main().
      * Use a forward declaration for each function that you call that you haven’t defined yet (covered in lesson 1.7).

  • Danu

    Ok, that clarifies things. Thanks for the help.

  • Danu

    Hey Alex. Why doesn’t the "getValuefromUser()" function execute when running the program below?

  • Reid

    I was not able to get the 2nd return code to work? I copied yours and it did not work either. I am using visual 2010. Is it even suppose to work?

  • Is it a good practice to use a void function only for printing results and not for calculating result (because void can’t return any value).

    • Alex

      At this point in the tutorials, yes, void functions are useful primarily for their side effects (e.g. printing stuff to the screen).

      Later on in the tutorials, you’ll learn about other C++ features that make that not true (for example, reference parameters and member functions).

  • begginner

    what is the problem with ithis program
    i want to take input through parameter
    [

    #include<iostream>

    int multiply(int x, int y,int z, int e)
    {
    return x*y*z*e;
    }
    int input(int s, int x, int c, int v){
    using namespace std;

    cout<<"enter a no";
    cin>>s;
    return input(s,x,c,v);

    }
    int  main(){
    using namespace std;
    int x,y,z,c;
    cout<<input(x,y,z,c);
    cin>>x,y,z,c;

    cout<<"the answer is"<<multiply(x,y,z,c);

    return 0;
    }
    ]

    • Alex

      Function input() should take no parameters and return only s. Right now it’s calling itself (which will loop until the program runs out of memory and crashes).

      You should call function input() four times in main, assigning the return value to x, y, z, and c respectively.

      Then you can call multiply(x,y,z,c) and it should work.

  • Silver_Douch

    if i will need to comment this out:

    std::cout << returnNothing(); // This line will not compile.  You’ll need to comment it out to continue.

    then why do we write it here from the begining?
    does it has some kind of purpose?
    cuz i set on it for a while and just couldnt come up with an answer myself!
    thanks for the help in advance!

    [code]
    #include <iostream>

    // void means the function does not return a value to the caller
    void returnNothing()
    {
        // This function does not return a value so no return statement is needed
    }

    // int means the function returns an integer value to the caller
    int return5()
    {
        return 5; // this function returns an integer, so a return statement is needed
    }

    int main()
    {
        std::cout << return5(); // prints 5
        std::cout << return5() + 2; // prints 7
        std::cout << returnNothing(); // This line will not compile.  You’ll need to comment it out to continue.

        returnNothing(); // okay: function returnNothing() is called, no value is returned
        return5(); // okay: function return5() is called, return value is discarded
    }
    [code]

  • newprogrammer

    Weird how you cant nest functions within other functions but you can nest calls to functions within other calls to functions

  • bobz

    Hi, Alex:

    In your "Let’s use these functions in a program" with 24 lines:

    What is the purpose of the curly braces on your lines 5 and 7?  Those enclose only a comment.  The comment on line 9 does not have any curly braces around it so it appears that comments do not require curly braces around them.  Does the opening curly brace which is on line 5 really belong on line 4?

    When I try to compile it with Microsoft visual studio express for windows desktop, I get two errors:

    Error    1    error C2144: syntax error : ‘void’ should be preceded by ‘;’
        
        2    IntelliSense: expected a ‘{‘        11    1    ReturnValues

    • Alex

      Comments are ignored by the compiler, so they can be defined almost anywhere (inside a function or outside of it).

      The body of a function needs to be enclosed in curly braces. In the case of returnNothing(), the function has an empty body, but it still needs braces to show that the body is empty. It’s pretty rare in C++ that you’d intentionally write a function that did nothing. In this case, it’s being done to show that functions that return void don’t need a return statement.

      Your code is erroring on line 7:

      You’ve got the start of a function declaration here with no body and no terminating semicolon. This is illegal syntax. You should remove this line since you already define a main() function on line 22.

      • bobz

        Thanks a lot, Alex.  Indeed that works.  I thought I had done a better job of inserting your example into the compiler.

        I think I was confused in that the line:

        and other similar are apparently NOT part of the body of the function.

  • Debojyoti Roy

    Sir,
        I cannot understand that why have you put the function call getValueFromUser() inside the variables x and y. And why the function getValueFromUser returns the variable a in line 11.
        Please help me as I am new to C++ programming.

    Yours
    Debojyoti Roy

    • Alex

      A function is a piece of code that can return a value back to the caller. In the above example, we’ve written a function called getValueFromUser(). When this function is called, it will ask the user to enter an integer, and put that value in a variable we’ve named ‘a’. At the end of the function, we return the value of ‘a’ to the caller.

      So who is the caller? In this sample code, there are two callers, one on line 16 and one on line 17.

      On line 16, we define a new integer variable named ‘x’, then getValueFromUser() is called, and the return value (whatever the user entered) is assigned to variable x.
      On line 17, we define a new integer variable named ‘y’, then getValueFromUser() is called again, and the return value (whatever the user entered) is assigned to variable y.

      Here’s what happens for a sample run:
      * The program starts at the top of main().
      * Line 16 executes. x is defined, and getValueFromUser() is called. The user is asked to enter a value, so they enter 5. The value of 5 is placed in variable a. This value is then returned back to the caller (line 16) and assigned to x. Now x = 5.
      * Line 17 executes. y is defined, and getValueFromUser() is called. The user is asked to enter a value, so they enter 7. The value of 7 is placed in variable a. This value is then returned back to the caller (line 17) and assigned to y. Now y = 7.
      * Line 19 adds x + y (5 + 7) and prints the sum of 12.
      * The program returns the value of 0 back to the operating system.

  • Mike

    I am VERY new to this world and am wondering how to best follow along with examples.  should I be creating new "projects" for each example or is there an easier way to add new pages to write code on.  the issue I am having is that when I select "new file" it is giving me errors from code written on previous files.

    any help for an utter novice is appreciated.

    • Alex

      My recommendation is to create a new solution for each example. It’s simpler than trying to add multiple projects to a single solution.

  • Chinmaya

    Hi your tutorial is extremely good.
    I know this question has been asked many times but there is a doubt still with me.
    If we declare namespace std then the standard namespace will be used…
    but what are the functions that are part of the std namespace.
    like if we use namespace std globally and use cout as a function then what will happen..
    i hpoe you understand and answer it there is an example..
    [code]
    #include..
    int cout()
    {
        some code here
    }
    int main()
    {
        calling cout()      {what will happen)
        some code here
    }

    • Alex

      You’re asking what will happen if our local program uses a name that has a naming conflict with something in the standard library. e.g.

      This causes a naming conflict, and the compiler will complain about cout being an ambiguous symbol. It doesn’t know whether to pick std::cout or the cout that we defined.

      In this example, even if you use “using namespace std;” inside of function main instead of outside, you’ll encounter the same issue. It’s why some people always just use explicit prefixes and avoid using statements altogether.

      • Chinmaya

        Thanks for the answer but there is one more question.
        Like

        what are the functions defined in standard library…

        • Alex

          There are tons of names defined in the standard library -- too many to list here. Plus they add more with every new version of C++.

          I’m not aware of any easy way to list them all out, since they’re scattered across many different files.

  • Niranjan.A.S

    Thanks again…..but hope it would get better if this chapter contained any tests or quizzes

  • Pranjal Rai

    When I run this code, the result is:

    Enter a number, sir.
    4
    tered
    Press any key to continue…

    The problem is wih the seconnd cout statement, the output never appears completely, like "You entered, 4"
    What am I doing wrong?

    • Alex

      should be:

      You can’t add a string literal and an integer using the + operator in C++.

  • Iamfokn lost

    #include <iostream>

    // void means the function does not return a value to the caller
    void returnNothing()
    {
        // This function does not return a value so no return statement is needed
    }

    // int means the function returns an integer value to the caller
    int return5()
    {
        return 5; // this function returns an integer, so a return statement is needed
    }

    int main()
    {
        using namespace std;
        cout << return5(); // prints 5
        cout << return5() + 2; // prints 7
      //cout << returnNothing(); // This line will not compile.  You’ll need to comment it out to continue.

        returnNothing(); // okay: function returnNothing() is called, no value is returned
        return5(); // okay: function return5() is called, return value is discarded
    }

    //why does it tell me 57? lol anyone?

    • Alex

      The key are these two lines:

      We’ve defined return5() to return the value 5.
      On the first line, return5() returns 5. We then send this value to cout to be printed. So what appears on your screen is “5”.
      On the second line, return5() returns 5, and then we add 2 to get 7. We then send this value to cout to be printed. So what appears on your screen is “7”.

      Because we didn’t print any spaces between them, the “5” and the “7” get run together, so it looks like “57”.

      It sounds like you’re treating “57” as a single number. But what’s happening is we’re printing the digit 5, and then printing the digit 7, with no space between them. Hence, what gets printed is “57”.

  • Thank you Alex for this great web site specially with the self educating like me\
    first of all i was know nothing about programing week ago
    and since i started i usually play with the code trying to produce my own 1st app using Visual studio 2010
    and have two issue
    1- i have successfully created a prog. to calculate the area and circumference of a circle and when i run it throw IDE (ctrl+F5) its perfect while when i try to run it throw the *.exe in the debug folder of the project its just flash knowing that i used cin.get() but nothing :/
    2- for the function  when i am trying to make a function called avg which create the average of two given numbers, the program is successful but the console request the inputs 2 times why is that happening if you can help
    Thanks again for the great work of this site
    .

    • Alex

      Hi Mostafa,
      1) Use this code to pause your program:

      2) You call function avg() twice:

      If you want three times the average returned with the first set of inputs, do this instead:

      • #include "stdafx.h"
        #include <iostream>
        int main()
        {
        using namespace std ;
        cout<<"Thank you Alex for the guidance"<< endl ;
        cout<<"Greetings From Egypt :)"<< endl ;
        return 0 ;
        }

  • Aakash Pandita

    First of all, thanks. Great tutorials.

    In the code under Reusing Functions, you equated the variable to the function, i.e, the return value of function to the variable.
    int x = getvaluefromuser()

    You did not separately call for the function to be carried out by writing it again but still the function was carried out as "Enter integer = " was printed.

    Isn’t it rather messy for the program to do something which we did not say?

    What if we only wanted to equate x to the return value but not carry out the remaining function?

    Thanks!

    • Alex

      Hi Aakash,

      I did call for the function to be carried out twice:

      getValueFromUser() reads a value in from the user and returns it to the caller. We call the function twice: once to get a value for int x, and once to get a value for int y.

  • Sausage

    Thank you so much for these tutorials! I’ve gone through some of the commonly recommended books for learning C++ but your website blows everything out of the water. It’s so much more approachable and…bite-sized 😀

  • In the example that includes the functions "returnNothing" and "return5", how come at the bottom, the function for "return5" does not return any value? Why is it discarded?

    • Alex

      Here’s the definition for the return5 function:

      As you can see, the return5 function returns the value of 5 when called.

      Later on, in the main() function:

      This is a function call to function return5. The return5 function returns the value 5. But nothing is done with this value. It is not printed or assigned, so it is thrown away.

  • Thanks Alex,

    I have never programmed anything except PLC ladder logic.  You have guided me this far without me having to ask a single question. well done mate your a champion.

    Stuey B.

  • Youssef

    Hi, I’ve got a problem.
    I don’t understand, in the code for calculating "y+x= " in the "GetValueFromUser" function, why is it "return a;" not "return 0;"? And what is the "a" for?

    • Alex

      In this function, on line 6, we define an integer variable named ‘a’. On line 7, we read input from the user and place it in variable ‘a’. And on line 8, we return the value that was placed in variable ‘a’ to the caller of the function (who can do whatever they want with it).

      Return 0 would always return the value 0 to the caller, but that’s not what we want in this case. Instead, we want the function to return the user’s inputted value to the caller, so we return the value of variable a.

  • razan

    1>---- Build started: Project: helloword, Configuration: Release Win32 ----
    1>  helloword.cpp
    1>helloword.cpp(7): error C3861: ‘return5’: identifier not found
    1>helloword.cpp(8): error C3861: ‘return5’: identifier not found
    1>helloword.cpp(9): error C3861: ‘returnNothing’: identifier not found
    1>helloword.cpp(10): error C3872: ‘0xa0’: this character is not allowed in an identifier
    1>helloword.cpp(11): error C2065: ‘ ‘ : undeclared identifier
    1>helloword.cpp(11): error C2143: syntax error : missing ‘;’ before ‘return’
    1>helloword.cpp(11): error C3861: ‘Nothing’: identifier not found
    1>helloword.cpp(12): error C2064: term does not evaluate to a function taking 0 arguments
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    why ??????????????

    • Alex

      Hard to know. Can you post your code?

      • razan

        #include "stdafx.h"
        #include "helloword.h"
        #include <iostream>
        int main()
        {
            std::cout << return5();
            std::cout << return5() + 2;
            std::cout << returnNothing();
        returnNothing();
        return5();
        }

        1>---- Build started: Project: helloword, Configuration: Release Win32 ----
        1>  helloword.cpp
        1>helloword.cpp(6): error C3861: ‘return5’: identifier not found
        1>helloword.cpp(7): error C3861: ‘return5’: identifier not found
        1>helloword.cpp(8): error C3861: ‘returnNothing’: identifier not found
        1>helloword.cpp(9): error C3861: ‘returnNothing’: identifier not found
        1>helloword.cpp(10): error C3861: ‘return5’: identifier not found
        ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

        • Alex

          You didn’t include the functions return5() and returnNothing().

          They need to be in your program, above function main().

          I’ll update the example to be more specific about this.

  • lekan

    Hi, tried to compile the return5()…returnNoting() in code blocks and i keep getting errors. i first tried to write it by memory, failed and copied it verbatim and still the same two errors.

    ||=== Build: Debug in ReturnNothing (compiler: GNU GCC Compiler) ===|
    C:\VC2015Projects\ReturnNothing\main.cpp||In function ‘int main()’:|
    C:\VC2015Projects\ReturnNothing\main.cpp|9|error: ‘return5’ was not declared in this scope|
    C:\VC2015Projects\ReturnNothing\main.cpp|11|error: ‘returnNothing’ was not declared in this scope|
    ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

    Help, dunno what im doing wrong.

    • Alex

      Did you paste them into different files?

      Try putting return5() and returnNothing() in the same file as main(), above the main() function.

  • Criboscel

    I get a fatal error LNK1120: 1 unresolved externals

    the code is as follows:
    #include "stdafx.h"
    #include <iostream>

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

    and when I’m using :
    #include “stdafx.h”
    #include

    int main()
    {
    using namespace std; // using directive that provides access to std::cout and std::endl
    cout << "Starting main()" << endl;
    doPrint(); // Interrupt main() by making a function call to doPrint()
    cout << "Ending main()" << endl;
    return 0;
    }

    I get an error C3861: 'doPrint': identifier not found
    WHY?

  • AaronHoffman

    #include "stdafx.h"

    int getValueFromUser()
    {
        using namespace std;
        cout << "Enter an integer: ";
        int a;
        cin >> a;
        return a;
    }

    int main()
    {
        using namespace std;
        int x = getValueFromUser(); // first call to getValueFromUser
        int y = getValueFromUser(); // second call to getValueFromUser

        cout << x << " + " << y << " = " << x + y << endl;

        return 0;
    }
    For some reason this wont work, it tells me that cout is not defined :/ even if i try to put it as std::cout it tells me cout / cin / endl isnt usefull for std.
    Microsoft visual studio 2013

  • Catreece

    Ugh, this one gave me a headache when I tried to test it. At first I was setting int = X, then trying to redefine X via a function with X defined within that function. What I've discovered is that each function has its own unique value of each variable, so my function can have a completely separate value for X that applies only within that function and is largely irrelevant to the main() function. Yay!

    That's a serious pain in the butt, since it means you have to define each variable within the function you want to actually use it in. It also took me awhile to figure out how to get it to perform the cin within a called function and have the output actually show up where I wanted it in the main() function.

    It SORT of made sense, but in a rather twisted way. I'd request an update to this explaining how to use a function to actually return a variable function which is of value, because this wasn't intuitive in the slightest.

    Anyway, here's what I finally came up with, which fixed the problem.

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

    int SetIntX()
    {
        using std::cin;
        // set X value to user defined choice
        // testing if x is relevant; believe each variable is unique to their own function
        int n = 0;
        cin >> n;
        return n; // confirmed; n value meaningless in relation to x
    }

    int SetIntY()
    {
        using std::cin;
        // set Y value to user defined choice
        int y = 0;
        cin >> y;
        return y; // further confirmation; y within function SetIntY() irrelevant to main()
    }

    int main()
    {
        // set cout to std::cout because I'm lazy :: also test that this statement works properly
        using std::cout;
        

        // test to make sure cin works the way cout does
        using std::cin;

        // Also, the above is a test of enclosed comments across multiple lines.

        // don't use the following when calling a function; need to set int X = function
        // int x = 0;

        // ditto to int x = 0
        // int y = 0;

        // ask user for a number,
        cout << "Enter a number: ";
        
        // No initialization takes place; the initial setting is set during the time the function is called
        int x = SetIntX();
        
        // ask user for a second number
        cout << "You chose ";
        cout << x;
        cout << " as your first number. Enter a second number: ";
        
        // User inputs Y value :: test for second variable and order
        int y = SetIntY();

        // adds totals and displays X+Y :: test for expression
        cout << "You chose ";
        cout << y;
        cout <<    " for your second number, for a combined total of " << x+y  << std::endl;
        return 0;
    }

    Final output successfully used the functions SetIntX() and SetIntY(), though it required not initializing the values in the first place, which was kind of weird. You'd think it'd just overwrite such, but it won't let you set the variable X multiple times, or at least not initialize it multiple times. Kind of a nuisance, but it works for now.

    Is there an easier way to deal with this? I can see this turning into a horrible mess if there needs to be multiple updates to the value of X.

    • Catreece

      Neat… I just realized I don't even need two functions for determining X and Y. Since they use the exact same methodology for determining the output, and apparently it doesn't matter what happens in the function itself as the output is saved directly to X, I can just reuse the SetIntX() function for both X and Y.

      I guess that's kind of the whole point behind using a function in the first place, though… so it seems a little silly in hindsight not to have noticed that. XD

    • Alex

      One challenge with “working ahead” is that some of the things you’re discovering (such as the fact that variables declared in a function only exist within that function) are explictly covered in section 1.4b -- A first look at local scope.

      > That’s a serious pain in the butt, since it means you have to define each variable within the function you want to actually use it in.

      Trust me when I say this is a good thing. If all variables were accessible across multiple functions, you’d start running into naming conflicts and/or functions could inadvertently change the value of variables they had no business touching!

      > I’d request an update to this explaining how to use a function to actually return a variable function which is of value, because this wasn’t intuitive in the slightest.

      I think I understand what you’re getting at, and this sounds like a good idea. I’ll update the lesson.

      • Catreece

        Yeaaaah… I discovered that shortly after. =P

        I can see the reasoning why you might not want to use variables all over the place to a degree, but honestly, there's nothing saying you can't name variables like totalScoreInGameMenu to ensure they're clearly only used in a single location.

        I dunno, just from my time with working with Maya, I really absolutely hate having the same name used in more than one place since sometimes things'll still break, even if they're attached to a completely different hierarchy, hence why naming conventions there tend to always have descriptive affixes.

        I realize that's not going to be the same across all programs, nor all languages (though it makes me curious since Maya runs off of Python and MEL, if those languages work the same way as C++ when it comes to naming variables), but it just reaaaaally bothers me to have a variable named X reused in twenty different places, even if none of them know that X exists in any of the other functions. I'd just rather have X consistently and clearly state what X is supposed to represent every time consistently across all functions so I can call on exactly that variable every time I want it.

        On the other hand, as you stated, I can see real benefits for keeping variables isolated, especially when it comes to memory management. Not having to store the variable permanently in memory and go looking for it every time you want it is probably rather handy, and utilizing functions to repeat tasks multiple times for different variable outputs means you can use a much smaller program for the same end result.

        Well, no point fighting it, and I can see why it'd be rather handy to have, it'll just take awhile to work through my head that it doesn't work the same way I'm used to thinking of things. I'll bet there's all sorts of handy little tricks that can be done with independent variables like C++ uses, it'll just take awhile to get used to the idea that X =/= X, except when within the same function.

        Also, thanks a ton for the quick replies! The site's remarkably useful in the first place, and getting quick feedback has been a great help too! ^.^

  • Sind

    I could understand the functions in C++.
    And it would be great, if you provide some info on function pointers as well. I am not sure, whether you have explained in the forthcoming articles.

    Also I never tried to look at function pointers, since I feel difficult by looking at them.

  • amin

    hi
    my question is why main in my complier doesn’t do well?
    #include “stdafx.h”
    #include “iostream”
    int main()
    {int x
    using std::cin>>”x”
    using std::cout<<"x+7";
    return 0
    }
    std::cout<<"well done!";

    • Alex

      I’m not sure what you’re asking. A few notes:

      * std::cout<<"well done!"; should be inside main. * "x" shouldn't be in quotes since it's a variable, not a string. * You're also missing semicolons at the end of most of your lines. * You can't combine a "using" statement with a call to std::cout/std::cin. Do one or the other.

  • ray

    when the compiler does some calculation, how can i get it to return a fraction instead of a decimal number. like 1/3 instead of 0.333333

    • Alex

      C++ doesn’t have native support for fractions.

      You could probably write your own rational number class, once you get that far in the tutorials. Or use one that already exists, like http://www.boost.org/doc/libs/1_43_0/libs/rational/rational.html

      Otherwise, you’re stuck with decimal values.

  • 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.

    • rameye

      I think it all depends on whether you want to keep your own global namespace for yourself, or give it all up to the std namespace. For these simple examples working solo in the comfort of your local machine it might not be evident, but in the real world you may be competing against the namespaces of many other programmers on a development team, and they can quite possibly be located on remote networks. If code is shared in a common namespace like std then painful name collisions will probably occur.

      If you keep your code under your own private namespace, and explicitly qualify names from other namespaces using :: like

      std::cout

      all will be well when your code is shared.

  • aborods

    Nice topic, I like it.

  • black_ant

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

    • Alex

      The operating system needs to know whether your program ran successfully or not. By convention, main returning a value of zero means success, and a non-zero number means error.

      This can be useful when writing a batch file or shell script (outside the scope of these lessons).

  • this was so helpful! thank you very much! 🙂

  • dj51401

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

  • mihirichathurika

    Thank you so much. you explain it simply

  • 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?

    • Chinmaya

      You are not returning a value in the function main()

  • Why do you use “using namespace std;” statement inside each function including main as well? Is there a reason? I think that using the statement as global at once time is more reasonable, isn’t it? For instance:

    #include <iostream>
    using namespace std;

    void print(){
    cout << "It is going to be written" << endl;
    }

    int main(){
    int a = 5;
    cout << "Value of a: " << a << endl;
    return 0;
    }

    Thanks in advance.

  • ProgrammerJupiter

    Can you return more than one value? like 2 integer variables that were both calculated in the function?

    • Alex

      You can only have one return value per function.

      However, there are ways to return multiple values. For example, you can put all your return values in a container and return the container. Doing this is a little more complicated though, so we don’t cover that until future lessons.

  • WordPress

    Alex, I love these tutorials.

  • Homesweetrichard

    can we write it like this “void DoPrint() {” please sense its easier to read both my mac and me. Since this is universally understood. programming grammar.

    Not like this
    “void DoPrint()
    {”
    Which is not universally understood grammar.

  • cooper507

    do you have to have a main() function in all programs?

  • cooper507

    what exactly does the command “endl” do? i have an idea but i would like to know precisely what it does.

    thx guys 🙂

  • cooper507

    ok guys quick question
    when you run this program why does the words “Starting DoPrint()” pop up before “In DoPrint2()” even the the DoPrint2()function is listed first?

    #include “stdafx.h”
    #include

    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;
    }

    • A Random Noob

      Because the DoPrint() function was called first by main().

      • WordPress

        The becomes virtually unnecessary when it comes to multiple functions being called. The main() function is ALWAYS the first function to start executing even if it may not be the first thing in the source code. Whatever function is called by main() will take action no matter what the order is in the source code. Order only matters inside functions.

  • Aditya

    why is declaring void main()
    illegal??

    my compiler has no problem in compiling it.

    also when we enter return 0;
    are we able to see it in the output screen??

    • lynx1241

      As the text above already stated, some compilers will let you get away with declaring main as void main(). But they will still interpret it as:

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

      Others will just generate an error.

  • Rose_

    Hi
    A funny thing is happening w/this code when I try to call and interrupt a call, the “In Doprint(), and In Doprint2() are continously rolling on the screen not stopping even w/esc. on keyboard. Stops when clicked on the console window.
    I don’t understand why this is happing. Be great if anyone can and please explain it to me.
    thanks.

    The Code:

    #include “stdafx.h”
    #include
    //Declaration of function Doprint()

    void Doprint()
    {
    using namespace std; // we need this in each function that uses cout and enel

    cout << "In Doprint()" << endl;

    }

    // Declaration of function Doprint2()
    void Doprint2()
    {
    using namespace std;
    cout << " Starting Doprint2()" << endl;
    Doprint();
    Doprint2();
    Doprint();
    cout << "Ending Doprint2()" << endl;
    }

    // Declaration of main()

    int main()
    {
    using namespace std;
    cout << "Starting main()" << endl;
    Doprint(); // this is a function call to Doprint()
    Doprint2();
    Doprint();
    cout << "Ending main()" << endl;
    return 0;
    }

    The Result:
    Starting Doprint2()
    In Doprint()
    Starting Doprint2()
    In Doprint()
    Starting Doprint2()
    In Doprint()
    Starting Doprint2()
    In Doprint()
    Starting Doprint2()
    In Doprint()
    Starting Doprint2()
    In Doprint()
    Starting Doprint2()
    In Doprint()
    Starting Doprint2()

    Press any key to continue . . .

    • Alex

      Your Doprint2() calls itself, so your program gets stuck in an infinite loop.

      • Sharjeel Safdar

        But why the execution of the programme has started from the "Doprint2()" function instead of the "main()"?

        • Alex

          It doesn’t. The program starts with main. However, because DoPrint2() gets stuck in a loop and keeps printing “Starting Doprint2()” and “In DoPrint()”, the first lines of main quickly scroll off the screen and are lost.

          If you use a debugger, and step through the program, you’ll see that the program does in fact start with main().

          • bharadwaj_pro

            I know that debugging means finding errors in the programs. But what is a debugger ?

            • Alex

              A debugger is a program that helps you debug your program. 🙂 It generally comes with certain capabilities, such as the ability to control the execution of your program line by line, and inspect the value of variables. That way you can see whether your program is executing the expected path, and whether your variables are getting the expected values.

  • rsenor

    thanks Nik!

    I am also totally new to C++.

    Does main always execute before the other functions in a program?

    • Alex

      Sometimes. It’s a simple question with a complicated answer.

      For the programs you are writing now, you can consider main() to be the first function that executes.

      There are some cases where other functions can execute before main. When your program is run, C++ may do some initialization before running main() to get everything set up. In some cases, this can involve calling other functions before main().

      For now, don’t worry about this.

  • winston

    why do i need to put “endl” at the end of somethings? It tells me too but when i dont it still works.

  • andrew

    Hi people . i mixed it up a bit with this lession . used bits from the last couple of lessions. which made it interesting . sorry if somone else posted somthing like this dident read all the comments.

    heres what i came up with .

    ps learning heaps thanks for the site .

    • Gizmo

      Hello, Andrew

      doprint() serves no purpose here.

      This would be easier to read and write.

  • Andrew Chmielewski

    when I click build it says it “succeeded” but it doesnt open up the run window to show it. What is wrong?

  • lsandling

    I have this really wacked question I must have missed something I can’t find Why don’t we put “using namespace std;” on the very top like right after our #includes ?

    • Alex

      If you did that, the using statement would apply to the entire file. That’s generally considered bad practice.

      By declaring it inside of a function, you limit the effect of the using statement to just the function, which is safer.

  • jack

    I already know Javascript and some normal Java but this is not responding to things like ‘cin’ and ‘end1’ in the ‘iostream’ library. Why?

  • Josh

    Do you always have to put all your functions above the main function?

  • Alex

    im writeing down for example “In DoPrint” bewten the cout and endl but i get red letters insteed of blue ones?? why?? im using visual c++ 2010
    i have done everything right

  • Jubjamie

    i have tried the following example in the tutorial but it just doesn’t work., What have missed?

  • db_z

    does cout mean ecout like in French

    • Dino

      I really hadn’t thought of that. Nice.
      Unfortunately Mr. Stroustrup (our beloved c++ father 🙂 ) is not as romantic. cout is simply (c)haracter (out)put

  • JPL

    Very well explained thanks for these tutorials:) Here is my first program using functions.

  • buck

    Hi Alex,
    Just wanted to add my thanks for a great tutorial.

  • Damien

    Hi Alex,
    Your tutorials are amazing and im going through them and understanding every bit. But where do i put this code?

    Let’s use these functions in a program:

  • Mike

    My code is exact same as his yet i get an end1 undeclared identifier error
    any reasons why? and i dont know to to do those tags but i did include the iostream thing and #

    include

    void DoPrint2()
    {
    using namespace std;
    cout << “In DoPrint2()” << end1;
    }
    void DoPrint()
    {
    using namespace std;
    cout << “starting DoPrint()” << end1;
    DoPrint2();
    DoPrint2();
    cout << “Ending DoPrint()” << end1;
    }

    int main()
    {
    using namespace std;
    cout << “Starting main()” << endl;
    DoPrint();
    cout << “Ending main()” << end1;
    return 0;
    }

  • joe

    is it normal for my ms-dos window to close right after i put in a number and press enter

  • Dude, just declare

    before the functions! It works for me. Thanks 🙂

  • Darrell