Search

1.4 — A first look at functions


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.

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 main 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() 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.

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

In the fifth 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.

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

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

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

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
Index
1.3a -- A first look at cout, cin, endl, the std namespace, and using statements

113 comments to 1.4 — A first look at functions

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

  • Fox

    These tutorials are fantastic :]

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

  • 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

    • You call DoPrint() twice -- once standalone, and once part of the following cout statement. Each time DoPrint() is executed, it prints “In DoPrint()”, which is why you see it twice.

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

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

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

Leave a Comment

  

  

  

1 × two =

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