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 the 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 a parameter list enclosed in parenthesis (). In this case, since none of our functions use parameters, the list is empty. We’ll talk more about function parameters in the next lesson. If you forget the parameters list, the function will not be called!

Return values

If you remember, when the main() function finishes executing, it returns an integer value back to the operating system (the caller) by using a return statement.

Functions you write can return a single value to their caller as well. We do this by setting the return type of the function in the function’s definition. The return type is the type declared before the function name.

A return type of void means the function does not return a value. A return type of int means the function returns an integer value to the caller.

Let’s use these functions in a program:

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

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

In the third function call, returnNothing() is executed. The function does nothing and returns nothing, so control returns to main().

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. You’ll need to comment out this line of code in order to make your code compile.

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

Returning to main

You now have the conceptual tools to understand how the main() function actually works. When the program is executed, the operating system makes a function call to main(). Execution then jumps to the top of main. The statements in main are executed sequentially. Finally, main returns a integer value (usually 0) back to the operating system. This is why main is 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. However, it is generally a good idea 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.

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:

1.4a -- A first look at function parameters and arguments
Index
1.3a -- A first look at cout, cin, endl, the std namespace, and using statements

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

  • I noticed you include this comment we need this in each function that uses cout and endl when you include namespace std;.

    Why do you include the library locally as opposed to globally? Are there functions in the library that conflict with other libraries that would cause a problem? Is it just a matter of preference? I hope I am not getting ahead of myself here.

    • That’s a very good question, actually.

      Just as with local/global variables, it’s better to declare things at a local scope if you can (and it’s not too onerous). It reduces the chance of inadvertently changing something you didn’t mean to, or having a name clash.

      While this is rarely a problem in small programs, in gigantic programs that run ten or hundreds of thousands of lines of code, your odds of having a strange name clash go up significantly.

      Probably the safest solution is to not use a “using” statement at all, and explicitly call the function with it’s namespace qualifier:

      std::cout << "Hello world!" << std::endl; But that makes for some ugly, harder to read code (and I haven't covered the scope qualifier yet!). Using a using statement at the function level is a nice compromise between safety and readability.

      • Claimcpp

        Well, in this case, can’t we merge libraries together? and then obviously if u can do that the computer will automatically detect duplicated function names, even if it can’t, you would manually be able to sort it out

        • Alex

          Generally you won’t want to merge libraries together. Libraries are generally designed to provide a set of functionality to do a specific job. Say for example you have a math library, and a sound library. It wouldn’t really make sense to put them together. And even if you did, it wouldn’t resolve the naming conflict (you’d just move the naming conflict into the library itself instead of in your program).

      • Syed

        Hi Alex,
        Thank you very much for this website which is no doubt best in the world for learning C++.
        I have a question about std::cout, when I run this code it print 0 as well.

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

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

        I know that if I dont call the function Hello() in cout it wont print the returned 0, but any other solution.

        Thank you

        • Alex

          does two things:
          1) It calls the Hello() function.
          2) It prints the return value from the Hello() function.

          The Hello() function prints the string “Hello World”, and then it returns the value 0, which main() prints.

          There are two things you should change:
          1) Function Hello() should not have a return type of int (it should have a return type of void, since this function does not need to return anything to the caller).
          2) Function main() should not print the return value of Hello(). A simple call to Hello() will suffice.

          • Imnoob

            #include <iostream>

            int dprint(){
            std::cout<<"welcome to he menu"<<std::endl;
            return 0;
            }

            int main() {
                std::cout<<"print the menu"<<std::endl;
                dprint();
                std::cout<<"end of menu";
                // your code goes here
                return 0;
            }
            This code did not print 0 as mentioned by above fellow Nd as explained by you. What’s wrong in it plz tell.

        • Ergo

  • Fox

    These tutorials are fantastic :]

  • Abhishek

    Fox is right 🙂

  • Person In Need

    Why is this not working?

    Ignore the include blank thing, I dont know why its doing that, I have iostream after that, this thing keeps erasing it..

  • Jefferson

    I think these are absolutely great tutorials, certainly the best I’ve ever found. Please keep up the great work Alex!

    I feel silly saying this, since I’m just starting out, but shouldn’t quiz questions one through three have
    using namespace std;
    statements in their main functions since they use cout and endl?

    • Thanks for the complements, and your question isn’t silly at all. If you wanted to compile these fragments, you’d need to add using namespace std; as well as #include <iostream>, but since they’re just code fragments rather than entire programs meant to be compiled I omitted the minor details.

  • sony

    what is the difference between the following declarations
    void show()and void show(void)

  • I come from a pretty decent background. I have had 7 years experience in my overall field. I know PHP/Javascript like the back of my hand…I wanted to get into C++ lately and I am working towards it. So far I love the language. The ONE thing I don’t like so far about it is having to put the main function at the bottom (or the other way you mentioned). It seems kind of unnecessary and definitely doesn’t sound like it’ll be very neat and manageable. The hard part is remebring to make a function before that…the one problem I would have is if I had 2 functions that called each other.
    In PHP you can have 1 function and then another function and because they are related sometimes each one of the functions ends up calling the OTHER function once. So that leaves you with something you can’t do in C++. You can’t make both functions above each other (impossible) so it won’t work like that.

  • Frostbite

    After studying your first couple of steps over night this is the code I managed to compile. Mind you I just started last night and never knew a thing about coding until now. I put did a combination of the three tests and heres what I came up with. It was very much enjoyable debugging and learning that the void must come before the main. Only takes one mind to expand a thousand others, thanks Alex much appreciated, cant wait to study further!
    ________________________________________________

    // Test subject.cpp : main project file.

    #include “stdafx.h”
    #include

    using namespace System;

    void Test()
    {
    using namespace std;
    cout << “Starting Test 2” << endl;

    cout << “What is the value of X x Y?” <> x;
    cin >>y;

    cout << “The correct answer is ” << x + y <<endl;

    cout << “Testing complete!” <<endl;

    system (“pause”);
    }

    int main()
    {
    using namespace std;
    cout << “Test 1 compiling…” <<endl;

    cout << “Compiling complete, starting Test2” <<endl;

    system (“pause”);

    Test();

    return 0;
    }

    ________________________________________________

    • Frostbite

      somehow in the transferring this typo came up:
      cout << “What is the value of X x Y?” x;
      should read:
      cout << “What is the value of X + Y?” <>y;
      cin >>x;

      __________
      not sure how to embed the code to make it look proper yet, so its still not working apparently

  • Rousseaux

    i’d like to see my previous comment w/ my .c proggie and how ppl rate it. Noobs need reinforcement

    PS i’m glad you mentioned “less than/greater than” is not a c++ operator, i couldn’t figure that one out though it would be cool if it worked. Can i # define it and add it to “iostream”?

    • Unfortunately, you can’t define <> as a new operator in C++. If you’re looking to do inequality (which is the only thing I can think of that would make sense for <>), you’ll have to get used to using !=

      • Rousseaux

        Nah, the way i saw that operator, , used was to define get a variable (for example from cin, and cout that variable. As Frostbite and Sumanyu did above.

  • Stefan

    Thank you so much. This tutorial is definitely the best out there!

  • Seltox

    I’ve gone through quite a few websites looking for tutorials.

    This one is by far the best i’ve ever seen.

    Alex, you are an amazing teacher. Everything here is clear, and the examples let you put it into practice, give you a template to do your own things with, and the quiz at the end is an excellent self-learning tool to make sure you actually know what you think you do.

    Only suggestion I could make would be to perhaps put a few more quizzes into pages that don’t have one 😉

    Thanks so much. I’ve been wanting to learn C++ for probably 2 years now. I’ve always had the motivation, but I could never find a tutorial that could get me over that first little step (past the Hello World! program ;)).

    ~Seltox

    • I appreciate your comments. I’d definitely like to go back and add more quizzes to the pages that don’t have them, and add more quiz questions to the pages that do. I’ve been prioritizing new content over quizzes, but now that I’m almost done with the initial content set (just have exceptions to do) I will hopefully have time for that soon. Thanks again.

      • Big"B"LuvRRR

        Hmmm, looks like you’ve *taken out* quizzes, too -- from this lesson, anyway!  Folks seem to refer to quizzes here that are no longer available…what’s happened to ’em, please???  Can be rather confusing reading comments when they refer to things no longer on the webpage….

        • Alex

          What actually happened was that the lesson was getting too long, so I split it into two parts. The quiz moved into the second part. When I split a lesson, I’ll try to match the comments with the correct part of the lesson, but it isn’t always possible.

  • Jose

    c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(19) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(19) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(20) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(20) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(21) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(21) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(25) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(25) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(27) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(27) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(28) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(28) : error C2065: ‘endl’ : undeclared identifier
    1>Build log was saved at “file://c:Documents and SettingsJoseMy DocumentsVisual Studio 2008ProjectsFunctionsFunctionsDebugBuildLog.htm”
    1>Functions - 12 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Any help?

  • adam

    If you define the value of x then call a different function will it remember the value of x? Because when I compile my infinitely increasing number loop I get this error:

    Here’s the source code:

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

  • Ravi

    Alex Sir,

    I have been observing that whenever you are calling a function,
    the function been called has been declared earlier in the program.
    Is there any specific reason that a function been called has to be
    present before it is been called…

    I mean to say that,

    If i call a function named “doprint2()” from a function;
    “doprint1()” and the function “doprint1()” has been coded before
    the function “doprint2()”. And then, i call the function would it affect
    it anyway..

    • A function must be declared prior to it’s use. However, it does not necessarily need to be defined before use.

      In all these examples I declare and define the functions before they are used because it keeps the examples easy. However, in future lessons, you will learn how to prototype a function so you can both use it and define it anywhere you want.

  • Darrell

  • Dude, just declare

    before the functions! It works for me. Thanks 🙂

  • joe

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

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

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

  • buck

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

  • JPL

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

  • 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

  • Jubjamie

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

  • 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

  • Josh

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

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

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

  • Andrew Chmielewski

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

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

  • winston

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

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

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

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

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

  • 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

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

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

  • WordPress

    Alex, I love these tutorials.

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

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

  • 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()

  • mihirichathurika

    Thank you so much. you explain it simply

  • dj51401

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

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

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

  • aborods

    Nice topic, I like it.

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

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

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

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

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

  • 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

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

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

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

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

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

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

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

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

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

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

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

  • Niranjan.A.S

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

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

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

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

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

  • newprogrammer

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

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

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

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

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

  • Danu

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

  • Danu

    Ok, that clarifies things. Thanks for the help.

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

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

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

  • Hridayesh Sharma

    Thanks alex i have got it
    these are nice 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.

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

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

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

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

  • 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • Nyap

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

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

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

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

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

  • 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

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

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

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

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

  • jeff

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

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

    }

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

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

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

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

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

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

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

Leave a Comment

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