Search

1.4a — A first look at function parameters and arguments

Function parameters and arguments

In the previous lesson, you learned that a function can return a value back to the caller via the function’s return value.

In many cases, it is useful to be able to pass information to a function being called, so that the function has data to work with. For example, if we wanted to write a function to add two numbers, we need a way to tell the function which two numbers to add when we call it. Otherwise, how would the function know what to add? We do that via function parameters and arguments.

A function parameter is a variable used in a function where the value is provided by the caller of the function. Function parameters are placed in between the parenthesis after the function identifier, with multiple parameters being separated by commas.

Here’s some examples of functions with different numbers of parameters:

An argument is a value that is passed from the caller to the function when a function call is made:

Note that multiple arguments are also separated by commas. The number of arguments must match the number of function parameters. Otherwise, the compiler will throw an error.

How parameters and arguments work together

When a function is called, all of the parameters of the function are created as variables, and the value of each of the arguments is copied into the matching parameter. This process is called pass by value.

For example:

When printValues() is called with arguments 6 and 7, printValues’s parameter x is created and assigned the value of 6, and printValues’s parameter y is created and assigned the value of 7.

This results in the output:

6
7

How parameters and return values work together

By using both parameters and a return value, we can create functions that take data as input, do some calculation with it, and return the value to the caller.

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

When function add() is called, parameter x is assigned the value 4, and parameter y is assigned the value 5.

The function add() then evaluates x + y, which is the value 9, and returns this value back to function main(). This value of 9 is then sent to cout (by main()) to be printed on the screen.

Output:

9

In pictorial format:

More examples

Let’s take a look at some more function calls:

This program produces the output:

9
6
15
10
7
6

The first two statements are straightforward.

In the third statement, the parameters are expressions that get evaluated before being passed. In this case, 1 + 2 evaluates to 3, so 3 is passed to x. 3 * 4 evaluates to 12, so 12 is passed to y. add(3, 12) resolves to 15.

The next pair of statements is relatively easy as well:

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

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

When the function add() is executed, the CPU needs to determine what the values for parameters x and y are. x is simple since we just passed it the integer 1, so it assigns x=1. To get a value for y, it needs to evaluate multiply(2, 3) first. The CPU assigns z = 2 and w = 3, and multiply(2, 3) returns the integer value 6. That return value of 6 can now be assigned to the y parameter of the add() function. add(1, 6) returns the integer 7, which is then passed to cout for printing.

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

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

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

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

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

Conclusion

Parameters are the key mechanism by which functions can be written in a reusable way, as it allows them to perform tasks without knowing the specific input values ahead of time. Those input values are passed in as arguments by the caller.

Return values allow a function to return a value back to the caller.

Quiz

1) What’s wrong with this program fragment?

2) What two things are wrong with this program fragment?

3) What value does the following program print?

4) Write a function called doubleNumber() that takes one integer parameter and returns twice the value passed in.

5) Write a complete program that reads an integer from the user (using cin, discussed in lesson 1.3a -- A first look at cout, cin, endl, namespaces, and using statements), doubles it using the doubleNumber() function you wrote for question 4, and then prints the doubled value out to the console.

Quiz Answers

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

1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

5) Show Solution

Note: You may come up with other (similar) solutions for #4 and #5. There are often many ways to do the same thing in C++.

1.4b -- Why functions are useful, and how to use them effectively
Index
1.4 -- A first look at functions and return values

217 comments to 1.4a — A first look at function parameters and arguments

  • Dan

    Great tutorials thus far. Question on Quiz #5 for you. Your solution obviously works fine:

    int doubleNumber(int x)   
    {   
        return 2 * x;   
    }   
      
    int main()   
    {   
        using namespace std;   
        int x;   
        cin >> x;   
        cout < < doubleNumber(x) << endl;   
        return 0;   
    }
    But -- when I do my solution, which is basically the same as yours but listed in a different order:
    int main(){
    	using namespace std; 
    	int x;
    	cin >> x;
    	cout < < doubleNumber(x) << endl;
    	return 0;
    }
    
    int doubleNumber(int x){   
        return 2 * x;   
    }
    I get a compiler error in MS Visual Cpp 2008 Express [error C3861: ‘doubleNumber’: identifier not found]. Now, when I move my “doubleNumber(int x)” function so it appears ABOVE “main()” like so:
    int doubleNumber(int x){   
        return 2 * x;   
    }  
    
    int main(){
    	using namespace std; 
    	int x;
    	cin >> x;
    	cout < < doubleNumber(x) << endl;
    	return 0;
    }
    it works fine. So my question is: I thought the placement of “main()” within the code isn’t supposed to matter? I thought I read that somewhere in your tutorials… But regardless where I think I saw that, it doesn’t make sense that “main()” would have to appear at the bottom of every piece of Cpp code. Am I overlooking something? Thx, -Dan
    • Dan, when the compiler compiles your program, it reads through the files sequentially. This means if it hasn’t encountered doubleNumber() by the time you try to use doubleNumber(), then it will give you an error.

      There are two ways to fix this:
      1) Put your functions above main()
      2) Use a function prototype. This means, put the function declaration int doubleNumber(int x); above main(), and leave the actual function definition below main(). That way, when the compiler encounters doubleNumber(), it will know what to expect, even if you haven’t actually defined how doubleNumber() is implemented yet.

      • Dan

        Thanks for the feedback, Alex. I understand what you’re saying.

        So generally speaking, when Cpp developers write their code, (the assumption I’m making here is that) they’re always putting their functions above “main()”? I would think that, by doing your fix #2 -- i.e. using a function prototype for every function -- that would create a lot of extra lines of code, especially when you get into software that has thousands of lines of code.

        So the practice among Cpp developers is to have “main()” defined at the bottom of all Cpp code?

        • When developing single-file programs, yes. But when you get into multi-file programs, things become a bit more complex. In the case of multi-file programs, the typical way of doing this is to put the function prototypes in a header file, and then #include the header file wherever you need access to those functions. I cover this in more detail in section 1.9 -- header files

          • derpasaurus

            Do you go over function initialization? (actually, I have no idea  about the correct terminology, but see below) eg.

            Also, should function or methods be used as default? Why/why not? (Meaning, should we put our function/method inside a class or not.)

            • Alex

              This isn’t called “function initialization”, it’s called a forward declaration. And yes, we cover it later in this chapter. 🙂

              You should use both functions and methods (functions inside a class) as appropriate. If the function belongs to a class, put it inside the class. If it doesn’t, don’t. By the time you learn about classes, you’ll likely understand what to do.

  • josh

    i’m dong question 5 how you said. At the moment it looks like this:

    #include

    int doublenumber(int x)
    {
    return 2*x;
    }
    int main ()
    {
    using namespace std;
    int x;

    cin >> x;

    cout

    But all I get when I run and build it is the hello world program.
    I keep writing these things but it never does what i want it to.
    Would you happen to know why it is doing this and how the problem could be solved?

    • It sounds to me like you’re compiling and executing the wrong program. Many IDEs let you have multiple projects open simultaneously -- however, only one project will be active/selected, and this is the one that will compile/execute. Make sure you have your doublenumber project active. Usually active projects have their names in bold.

  • Masss

    Hi Alex,

    I was just doing question 5 of the quiz like everyone else, but the problem is that when I input a number the window closes once immediately after it displays the answer. I know you have to add the statements like cin.get(); cin.clear(); and cin.ignore(255, ‘/n’);, however, it does doesn’t prevent it from happening. Heres my coding.

    I tried adding cin.get, as I have commented. THANKS

  • NeoLogic

    I’m a complete n00b when it comes to programming.. I find it very interested how there are many different ways of getting the same work done.
    My answer to question 5 is totally different, but still works: I just think my way could be considered Bloatware. I’ll just have to learn how to be
    more effecient.

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

    Anyway, I love your tutorials. I tried learning Pascal from a text book. I gave up before the first chapter. I think I might have a change using your tutorials,

    Thanks!

  • Leonora A Quarcoo, US

    i am having problems with this code can Alex please can you help
    tell me what i am doing wrong thanks
    the line cout Double number (

    • It look like you put your Doublenumber() function right in the middle of your main() function. Functions can’t be nested in C++.

      Just move Doublenumber() above main() and you will be one step closer.

      Also, when you call Doublenumber, it should be like this: Doublenumber(x)

  • Hasan

    Peace be upon you

    It’s good place to learn and good exam

    However it’s my answer for question number 5

  • gomezpcs

    In the beggining of this tutorials page you start of with DoPrint functions and you do a great job explaing it. all the sample code is complete and ready to compile. when i reach the Return Values and Parameters examples you have incomplete code that cannot compile? Why wasnt it written in complete ready to compile form?

    This gives me an error because u do not define X and y!!?

    1>---- Build started: Project: HelloWorld, Configuration: Debug Win32 ----
    1>Compiling…
    1>HelloWorld.cpp
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(22) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(22) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(23) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(23) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(24) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(24) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(28) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(28) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(30) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(30) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(31) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(31) : error C2065: ‘endl’ : undeclared identifier
    1>Build log was saved at “file://c:\C++2008\HelloWorld\HelloWorld\Debug\BuildLog.htm”
    1>HelloWorld - 12 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    What gives? Am I an idiot? Or is there a reason y u didnt write the code out completely?

    • If you look at the errors your compiler is telling you, it’s not complaining about x and y, it’s complaining that it doesn’t know what cout and endl are. In order to define those, you have to #include and use the “using namespace std;” line.

      I fixed the example and made it a complete program so it will compile.

  • Ravi

    Alex Sir,

    The following code doesn’t seem to work properly…
    It takes in all the instructions and data..but, doesn’t provide me with
    the result i.e .. the addition of the two numbers…
    plz help..

    • The problem is your function does not print the results of a+b, it just return it to main(), which doesn’t do anything with the result either.

    • Ivan

      There are of course more ways to solve the problem but i was into using the existing code….
      far too lazy… and its quite late.. XDD

  • Jon

    heres my code

  • Leonora A Quarcoo, US

  • Steve

    hi alex.

    I’m doing question 4 and it doesn’t seem to work. i have

    This is my error:

    1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
    1>C:\VC2008 PROJECTS\HelloWorld\Debug\HelloWorld.exe : fatal error LNK1120: 1 unresolved externals
    1>Build log was saved at “file://c:\VC2008 PROJECTS\HelloWorld\HelloWorld\Debug\BuildLog.htm”
    1>HelloWorld - 2 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • csvan

      You have to add a main function which calls your function (doubleNumber()), and you should also add using namespace std; after the #include statements. A C++ program cannot (at least I know of no such thing) be run without a main function, because that is the actual function being called by the operating system!

  • Teclo

    I’m confused by this:

    int add(int x, int y, int z)
    {
        return x + y + z;
    }
    
    int multiply(int x, int y)
    {
        return x * y;
    }
    
    int main()
    
    {
        cout << multiply(add(1, 2, 3), 4) << endl;
        return 0;
    }

    Can you explain how x, y and z are being attributed there. I thought you had to say x = 7 or whatever, but here there’s nothing like that. Is it down to the order you write x, y and z in along with the order of the numbers later on? Or will it just attribute the values to x first, then y, then z, no matter what order you wrote them in (e.g. z, x, y)?

    • csvan

      When you call the function add(int x, int y, int z), the compiler is expecting 3 integer values within the parentheses, in that exact order, separated by commas. The integer values that are passed this way are in turn assigned to x, y, and z.

      Thus, when you write this call: add(1,2,3), it is equivalent to add(x = 1, y = 2, z = 3), and the functions will treat these variables (x y and z) as having those values, as long as the function is running.

      In other words, by calling add(1,2,3), you are really giving values to the variables in question, just as it should be.

      It helps if you try to think of functions as separate from each other, just like Alex explained: A function returns a value to the caller, and the caller can pass parameters to the function being called. What this means effectively is that x, y and z are variables LOCAL to the function add (not main()!), and main simply helps the function add by telling it what value it should give to its variables.

      Hope that helps! Send a mail otherwise (csvanefalk@hushmail.me). Of course, you should also ask Alex, I don’t know how often I will be checking these comments!

  • GlassJoe

    Thanks Alex!
    I compiled my first little program for Quiz Question 5 and it was great: worked like a charm and basically matched your solutions!
    But then I showed it off to my girlfriend… She entered an unfathomable positive number in the console (to be doubled), but the result came back negative.
    What’s going on to cause this? When I use integers of a smaller magnitude everything seems to work perfectly.

    Just curious. -Joe

    • Ron

      I may be wrong on this, but I think this is because of “rollover.” in other words, there is a maximum value that can be stored as an integer, and as I read somewhere else, when you perform an operation on a positive integer that makes it larger than the max, it rolls the number over to the smallest number (kinda like an odometer). In the case of integers, its a negative number.
      I first learned MATLAB programming, and when you went overboard there, it just returned “inf” for infinity. At least with that I could understand what had happened lol.

    • madryoch

      Hmm i hope this helps. When you type int variableName; it creates a reference in RAM for variableName and occupies a specific number of bytes for int types.Either you initialize the variable or not, the number of bytes occupied by the variable are specific for ALL variables of a specific type.Now There are types of int … e.g. unsigned short int and signed short int both take same bytes in RAM which means they can hold up to a specific maximum of different numbers.
      Unsigned short int range = numbers from -32768 to 32767. Total numbers stored = 32767-(-32768)= 65536 numbers
      Signed short int range = numbers from 0 to 65535. Total numbers stored = 65535 plus one which would be the number zero = 65536 numbers total…

      So when u type int the compiler automatically sets it to signed int…
      What happens then when u make mathematical equations that exceed the limits ?
      The extra digits of the calculations are overflowing so they never get saved… which results in the following for signed short int…

      Let’s say we have a result of 32768…= 32767+1 so it restarts at -32768.
      Further Explanation with binary system…

      number 15 = 1×8 1×4 1×2 1×1 = 1111 in binary digits
      number 16 = 1×16 0x8 0x4 0x2 0x1 =10000 in binary digits

      Imagine now that u can only keep 4 binary digits(ammount of memmory space a variable of specific type takes) …
      So 10000 that has 5 digits looses the first digit and is saved as 0000. Number 0 in decimal
      4 binary digits means numbers from 0 to 15 (16 total numbers) That way if u try to store a larger number the counter will start anew as explained above…

      Sorry if my explanation is not very good . English is not my native language but i really hope u understand how it goes…

  • Anon

    Why doesn’t this work?

    • rose

      you used two parameters in doubleNumber function definition, but during function call only one parameter..number of parameters must be same.
      and also doubleNumber must return a value.

      • Alex

        Correct. The last line of main should be:

        Because you’ve defined your function to take two parameters, and if you want to double z, you need to pass in 2 as the second parameter.

        That said, it’s weird to call your function doubleNumber when it actually multiplies two numbers (one of which may or may not be 2).

    • 1DoRa

      There are 2 problems in the code.

      1) You did not return anything in doubleNumber fucntion
      2) last line in the main() function, you did not pass the values properly

      Here is the correction

      • Chinmaya

  • Dino

    First of all kudos for the great site you have.
    I had a little problem with exercise 5. My solution was this:

    The problem is that the value is not doubling. Doing a debug, I saw that the function was called correctly, x was calculated as it should inside the function, but never returned to main. Doing a x=myFunction(x) resolves it, but I don’t understand why? If I’m simply using a myFunction(x) isn’t x supposed to get the new value calculated inside the function?

    • madryoch

      Try using x=doubleNumber(x); instead of doubleNumber(x);

      or

      Remove doubleNumber(x); and correct the following to:

      cout << "The result is " << doubleNumber(x);

      The reason this happens would be if i am not mistaken that x variable in doubleNumber function is active only while in the function itself so when the control returns to main the x in main being a different variable has the set value of what u ve inserted with cin.
      Note that the returned value of ur doubleNumber function is not saved anywhere thus is not accessible…

      So the solution is either assign the returned value to x in main function or ask from cout to execute the doubleNumber function and print the returned value right away…

      Hope i helped… 🙂

      • Big"B"LuvRRR

        But the x in doubleNumber() is **returned** to main() so I don’t understand how what you say explains the issue.

        Why does

        work but

        doesn’t???

        • Big"B"LuvRRR

          Uh, never mind -- Alex’s explained it below: the x is indeed returned in the second situation but its value is the same one that was originally passed into the function because the computer must be told (via a statement like "x = x * 2;") that x will now have a new value!

  • Jil

    when we write a program like this, it will not work

    #include “stdafx.h”

    #include “iostream”

    int main()
    {
    using namespace std;
    int numb,a;
    cout << "Enter number" <> numb;
    a = doubleNumber(numb);
    cout << a;
    return 0;
    }

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

    • Jil,

      In the third line,

      should be

      .
      Also, int main() should be at the bottom of the program. (or write

      under the
      #include .

      I hope that helps.

  • Marco

    hey i have a problem with the following code:

    it gives me this error:
    In function “int main()
    “multiply” undeclared (first use this function)

    I don’t understand what went wrong

    • Howard

      Marco, you misspelled multiply when you wrote the function. But you spelled it correctly when you called it from main. So the compiler was expecting a function called multiply, which doesn’t exist in your program, although one called multipliy does. To fix the error, either change the function name to the correct spelling, or misspell it the same way in the function call. I’d go for my first suggestion, though either will work.

    • Gizmo

      Hello, Marco its just a typo. You misspelled multiply

  • Leo

    These tutorials are incredibly well constructed and very easy to understand. Many thanks to the author! I also love the quizzes! Here’s what I came up with for #5:

  • AlkieP

    On solution 5 you have two solutions to do the same thing:

    This,

    and this:

    I understand that this is a small simple program where performance isn’t an issue, but if hypothetically this was a program with a much larger scale, is there a difference in speed/performance between these two techniques? The first one seems shorter, and therefore faster?

    • Alex

      The program with x = doubleNumber(x) has an extra assignment operation that happens, so it would be slightly slower.

      The speed difference would likely be unnoticible unless you were running this thousands of times.

  • Lenny

    I love my solution for question 5:

    Nice Tutorial so far!

  • DarkOwner94

    Hey nIce tutorial i am understanding it 🙂
    btw here is my code for solution 5 -.^

  • me

    finally! addition of 2 numbers

  • Bryan

    Here is what I came up with for question 5

  • Hey, I’m new to C++, and I answered question 5 as follows:

    It works, but is not included in the answers…so, is it a correct way?

    • Alex

      If you define “correct” as producing the right answer, then it looks correct. There are usually many ways to do the same thing in C++. Sometimes one way is better than another, but other times, it’s just a matter of preference.

      You could improve this program by getting rid of line 12 (int y=2) and changing the last line to:

  • cooper507

    in the piece of code, for example:

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

    does it matter that when you create a function you have the (int x, int y) in the parenthesis? what does it do for the function?

    heres another example:

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

    • Alex

      (int x, int y) are the function parameters. Without them, the compiler won’t know what x and y are inside of the add() function, and you won’t be able to pass values into add().

  • ingthinks

    Here is my solution to #5:

    #include “stdafx.h”
    #include

    int doubleNumber(int x) // doubles value of x
    {
    return x * 2;
    }

    int main()
    {
    using namespace std;
    int y; // declares variable y
    int x; // declares variable x
    cout <> x; // defines x as users input
    y = x; // defines y as equal to x to display the number that was doubled
    cout << y << " doubled is " << doubleNumber(x) << endl;
    return 0;
    }

    • You don’t actually need y, as you can simply do this
      cout << x << " doubled is " << doubleNumber(x) << When you take the x the first time, it will hold the original number, when you use doubleNumber, it will output the result of x * 2.
      That way the code is more optimized, as it requires less memory to hold the values, and it will no longer need to assign the value of x to y, which is a waste of CPU cycles (I know that in this case the difference will be a nanosecond at most, however in bigger programs this difference might be seconds).

      • ingthinks

        i see, thanks for helping me to understand this better
        here is my updated code:

        #include “stdafx.h”
        #include

        int doubleNumber(int x) // doubles value of x
        {
        return x * 2;
        }

        int main()
        {
        using namespace std;
        int x; // declares variable x
        cout <> x; // defines x as users input
        cout << x << " doubled is " << doubleNumber(x) << endl;
        return 0;
        }

        same functionality as my original program but i can see how this is a better way of doing it

  • ingthinks

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

    int doubleNumber(int x) // doubles value of x
    {
    return x * 2;
    }

    int main()
    {
    using namespace std;
    int x; // declares variable x
    cout << "Input an integer to double: ";
    cin >> x; // defines x as users input
    cout << x << " doubled is " << doubleNumber(x) << endl;
    return 0;
    }

  • WordPress

    Alex, are parameters only used for mathematics?
    By the way, I found out a way to calculate the addition of two numbers with only one function =D

    #include(less than)iostream(more than)
    #include(less than)conio.h(more than)
    using namespace std;
    int main(){//returns 0
    double dA,dB,dC;
    cout<>dA;
    cout<>dB;
    dC=dA+dB;
    cout<<dA<<" + "<<dB<<" = "<<dC<>dA;
    cin>>dB;
    dC=dA+dB;
    cout<<dC;
    }

    • WordPress

      ?? My code’s gone haywire… Let me retype it here:

      int main()
      {
      double dA,dB,dC;
      cin>>dA;
      cin>>dB;
      dC=dA+dB;
      cout<<dC;
      system("pAuSe";
      }

    • Alex

      Parameters can be used for all kinds of purposes. Mathematics just makes for easy examples because (almost) everyone intuitively understands how to add and subtract small numbers.

  • Lakshya

    here is my code :

  • Yahsharahla

    Hi I decided to post mine since it looks like I chose a different way to make this program but with the same results.

  • Grif

    Very much a beginner here, but there’s something I need a little clarification with - switching the order of “main()” and “add(x, y)” in the code seems to cause an error (I was trying to input it that way due to my own OCD wanting main to be up the top of the code).

    The result seemed to be that “main()” had no idea that “add(x, y)” even existed unless “add(x, y)” was assigned/created in code *before* “main()”.

    Is this always the case? That “function a” trying to call “function b” requires function b to be defined (and placed literally above function a’s code in the editor) before it’s run?

    • sjm71

      Yes, this is always the case. You can also use function prototypes before “main()” instead of writing the full funtion definitions and the write the funtion definitions after “main()”…

      #include

      //Function prototypes…
      int add(int, int); // NOTE: the semicolon (;) at the end!

      int main()
      {

      return 0;
      }

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

      Hope this helps?

  • xPrezidential

    Here’s my code for quiz 4 and 5. Give me feedback on it, please. I just began C++ today.

    --------------------------
    #include “stdafx.h”
    #include

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

    int main( )
    {
    int integerToDouble = -1,
    theResult = -1;

    using namespace std;
    cout <> integerToDouble;
    cout << endl;

    theResult = doubleNumber( integerToDouble );

    cout << "The doubled value of " << integerToDouble << " is " << theResult << "." << endl;

    system( "PAUSE" );
    return 0;

  • ballooneh

    does the doprint function have to be typed before the main function?
    Also, does doprint have to be capitalized?

    • Alex

      For now, doPrint() has to be declared before the main function. I’ll discuss how to get around this restriction in later sections.

      doPrint() doesn’t have to be capitalized. It could be called doprint() or do_print(). C++ is case-sensitive though, so doprint() and doPrint() would be considered two different functions.

  • majadood

    #include

    int multiply(int x, int y)
    {
    int product = x * y;
    int another_variable = x * 2;
    }
    int main()
    {
    using namespace std;
    cout << multiply(4, 5) << endl;
    return 0;
    }

    This compiles and gives the answer 8.

  • SivaSankar

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

  • Jupoopiter

    Superb tutorials!

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

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

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

  • Slyfvro

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

  • toastedsub94

    Ehhh, wow mine was overly complicated.

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

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

  • thebadlizard

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

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

  • kenwhite23

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

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

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

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

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

    • kenwhite23

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

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

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

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

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

  • harman

    i did the lesson and tried to make my own code, but i cant seem to get the right answer. Plz help me out. What i was trying to do was to get a user to input a number (x) which would the get doubled and be added to y=5. But its instead giving me a strange number.

    • Ty Ler

      I ran your code and its fine. Your problem could be from line 2 not containing anyhting after that include statement.

    • Reeti

      You need to include the library to access cout , cin and endl since they reside under the namespace std which resides in iostream. When you write #include <iostream> , the compiler knows where to look for cout , cin and endl.

  • Steve

    Great tutorial, thank you. 🙂

    Found typo it seems.
    Search on page for: multiple(2, 3)
    In that example the function is “multiply” but appears to be typo on line 19 calling multiple(2, 3).

  • Martin

    Visual studio 2010 won’t let me make a “}” in the code writing sections.

  • Catreece

    Whelp, that's clearly it for me for today, my brain has officially started being stupid. =P

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

    int SetIntN()
    {
        using std::cin;
        int n = 0;
        cin >> n;
        return n;
    }

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

    int multiply(int Na, int Nb)
    {
        return Na * Nb;
    }

    int main()
    {
        using std::cout;
        cout << "choose x: ";
            int x = SetIntN();
            cout << "you chose x: " << x << " " << std::endl;
            cout << "choose y: ";
            int y = SetIntN();
            cout << "you chose y: " << y << " " << std::endl;
            cout << "Constant Z multiplies your answer by 3" << std::endl;
            cout << "your final answer is: " << x << " + " << y << " * " << 3 << std::endl;
                cout << multiply(add(x, y), 3) << std::endl;

                return 0;
    }

    Looks great! Tested it with ((5 + 6) * 3) and it kept coming out to 33! I was trying to figure out how it messed up 5*6=30 and where it was getting that extra 3 from… for about 10 minutes before I realized, waaaaait a second. My program's feeding me the right answer, I'm just too inattentive to perform basic math in my head. Oops.

    On the plus side, it worked right. XD

    It was surprisingly easy to chain together the arithmetic functions like that, however. I expected to see big mess when trying to feed variables into it instead of integers, or when mixing variables and integers together, but no problems at all other than I apparently can't add and multiply. =P

    Pretty sad when you have an easier time understanding new programming functions over basic math you learned before even entering grade school.

    Regardless, thanks again for the tutorials; they're really making this pretty easy and they make a lot of sense. Any time I get hung up on something it's invariably because I'm trying to do stuff that hasn't been explained yet, or testing out something I'm not supposed to, rather than due to any issues with the tutorial information itself. As such, I have only myself to blame, and I can live with that. XD

  • Daniel

    Hello Alex,

    Thank you very much for these fantastic tutorials, I am slowly working my way through them and have a question in regards to the functions for simple things such as addition, division,multiply.

    At least in the context of these tutorials, why can one not simply put…

    cout << x * 2;

    cout << x + y;

    I have tried the above (after assigning a value to x and y of-course), I still get the same result as I would have done when using a function.

    Are there examples where the method above would be favorable over the creation of functions?

    I can sort of see where a function would be useful in describing/showing why something is being done, but this could easily be done with comments.

    At first I thought it would be for reusing the function with different variables for example in a game where you want to double several scores or items, but wouldn't you then have to include the variables within the function so that it gets returned what it expects?

    It just seems like extra work.

    I hope i haven't shown a huge misunderstanding of programming by asking this question. I just want to be 100% in the understanding of why I am doing things a certain way.

    Kind regards

    Daniel

    • Daniel

      Ignore my last comment, I understand now.

      You discuss the answers I was looking for in one of the last paragraphs (I did this section late last night!)

      It was going through Catreece' program above that made me appreciate how using functions can clean up code the more complex it gets.

      Then after reading the whole page again it just clicked :).

      I must say making a program is a completely different animal to simply being able to code, my grey matter is taking a right hammering XD.

      Kind regards

      Daniel

  • Delvin Bonilla

    Well, I'm following the tutorial here to further improve myself in my Computer Science class and I feel very happy with these tutorials. I learn more here than in my class to be honest. I feel accomplished with my finals solution to #5:

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

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

    int main()
    {
        int x;
        cout << "Enter number you wish to double:" << endl;
        cout << " x= ";
        cin >> x;
        cout << "Your double variable is equivalent to " << doubleNumber(x) << "." << endl;
        return 0;
    }

  • Souvik Pal

    Dear Alex,

    Sir,This is the best place to learn programming from beginning . I know java, c and so learning C++ is getting much easier , One thing that i noted that every language has most of the thing in common and if one knows a language they can learn others easily.
    I wish you put on some other programming language tutorials online.
    It would be very nice if you put on some more complex programs of real life or suggest me some good books for c++ and python.
    Thank you,

    Souvik..

  • Chris

    Hi Alex,
    Loving the tutorials. I’ve been wanting to learn how to program for many years (didn’t know it though) and now I’m finally able to because of this awesome tutorial.

    Here is the solution I came up with for Question 5

    Oh and I figured out my error with visual studio as to why it shutting down my console immediately. I was starting my programs with debugging and not building them first either. Thanks again Alex!

  • [code cin >> x;
        cout << doubleNumber(x) << endl;]

    OMG, who can tell me how to type coding style in the comment ?

  • Nagidal

    I think that the function doubleNumber cannot be of int type. It has to be able to take *any* integer and return its double value. That includes also large (signed) integers like 2147483647 (31 bit long integer). Hence doubleNumber must be of long (or even long long) type:

    • Alex

      The implementation of doubleNumber() above is flawed, as you correctly point out.

      For now, that’s okay. We’re more focused on function basics (parameters and return values) than on other data types (such as long long), overflow, and conversion between types. We’ll get to all of those things later.

      At this point in the tutorials, simplicity wins the day. 🙂

  • Aakash Pandita

    Hey!
    Regarding the second method in quiz 5).
    I don’t understand how this works:
    x = doubleNumber(x);

    I have been thinking really hard with respect to mechanism and I am not able to understand.
    It’s like writing x=2x.
    Please help.
    Thanks!

    • Alex

      x = 2x does makes sense if you think about it like this: x = (2x). Whatever value is in x, double it, and then assign that value back to x.

      So if x starts as 5, we double it to 10, and assign it back to x. x now equals 10.

      The function call is doing exactly that.

      • Aakash Pandita

        Thanks! I understood.
        But I still find it tricky as we are doing two things at the same time in

        It would work if the program first evaluates doublenumber() and then equates it to x.
        It won’t if it does the other way round.
        How does the program know what to do first.
        Or does it do both at the same time?
        Am I over thinking it?
        Thanks!

        • Alex

          You aren’t overthinking it. On the contrary, you’re thinking ahead. 🙂

          C++ has a set of rules that it uses to evaluates all expressions. How this works is covered in section 3.1 -- precedence and associativity.

          In this case, the evaluation of doublenumber(x) always happens before the assignment, because evaluation of functions is higher precedence than assignment.

  • Aakash Pandita

    Thanks!

  • MD jYa

    plz reply me where  i have done mistakes???

    #include <iostream>

    int readanInteger()
    {
      std::cout<<"enter an Integer"<<std::endl;
      int a;
      std::cin>>a;
      return a;
      
    }

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

    int main()
    {
      
        int x;
        doubleNumber(x);
        std::cout<<doubleNumber(x)<<std::endl;
        return 0;
    }

    • Alex

      You’re passing an uninitialized variable x from main to doubleNumber(). You’re then initializing the variable inside doubleNumber().

      Instead, you should initialize x in main(), and then pass that value to doubleNumber.

  • Jordan

    When I compile the code I’m getting a blank black screen in  cmd…..

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

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

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

    • Alex

      You’re getting a blank screen because the line:

      is waiting for you to enter a number.

      If you change your main() function to this:

      The output will make it clearer why your program is waiting.

  • Danie Malan

    HI

    When i compile i get the following error that seems to refer to the main function that was in the code when the project was open. I replaced this with my own code.

    Error    1    error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup    c:CppProjectstest14atest14aMSVCRTD.lib(crtexe.obj)    test14a

    Error    2    error LNK1120: 1 unresolved externals    c:CppProjectstest14aDebugtest14a.exe    1    1    test14a

    The initial code when opening the project is:

    // 14atest.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"

    int _tmain(int argc, _TCHAR* argv[])
    {
        return 0;
    }

    The code i replaced it with was:

    // 14bDouble.cpp : Defines the entry point for the console application.
    //

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

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

    int Main()
    {
        using namespace std;
        int x = 0;
        cout << "Please enter a number" << endl;
        cin >> x;
        cout << x << " * 2 = " << DoubleNumber(x) << endl;
        return 0;
    }

    How can i solve this

  • Danie Malan

    Thanks it works.

  • bobz

    Nitpick regarding Quiz question 5:

    I was searching section 1.3 for cin. (more difficult because "search" or "find" was not working for some reason).  Could not find it there.  I think you mean to say that it is discussed in 1.3a?

    Thanks,

    BobZ

  • I did question the way you have done it in codeblocks and in another compiler, i dont get any output. Then i erased the int x and cin>>x and just wrote cout<<doubleNumber(1)<<endl and i get the right output. How did this happen?

    • Alex

      cin >> x is waiting for you to enter something from the keyboard, so it can put what you enter in variable x.

      If you type in a number and hit enter, your program will continue.

  • Ed

    Thanks for the Tutorial love it so far, this has been the best website i have ever found. Thank you for helping us noobs with this!…

  • Usman Haider

    My solution to question 5 was

  • R00kie

    Hi Alex ! I would love it if you could answer my question , I noticed a very odd thing…

    Using what you taught me I wrote this piece of code that adds two numbers without defining a value for the 2 variables and what I find amazing is that every time I run the code the first variable (X in my case) is automatically assigned to the value of 1 and the second (Y) is random like it should be..

    Why is the computer always giving the value of 1 to X ?? I know why the Y value is random, but why is X always 1 even though I never defined X as being 1…Please let me know what you think, I am running it via Visual Studio 2010 and every time the result is 1 + Random y

    The same thing happens if I multiply or divide , the computer always makes the same choice making x= 1 and gives y a random value like it supposed to….why isn’t x random as well ?

    Also when dividing x/y , the result is 0, which is not slightly accurate to say the least..

    int add (int x, int y)

    {

    return x + y;

    }

    int main(int x, int y)

    {
        std::cout << x << "+" << y << "=" << add (x,y);

        return 0;

    }

    • Alex

      The answer is due to the fact that you have parameters on main(). So far, I’ve only talked about main() functions with no parameters. However, main() can have parameters, which is used for processing command line arguments.

      When main has parameters, the first parameter represents the number of command line parameters. That’s why your x is set to 1 -- your program always has 1 parameter (the executable name). If you were to run your program with additional parameters, x would be some other number.

      For now, you shouldn’t have any parameters on function main(). Personally, I’m surprised it even compiles, since your second parameter has the wrong type.

  • Boria

    hello Alex,
    about question #5:
    its the first time i saw you using "main()" two times in one code!
    didnt you say that only one main can be used in a program coding?

    • Alex

      Yes, a program can only have one main() function.

      The second main was meant to be an optional way of solving the problem. I’ve commented it out to make it more clear that it’s an optional solution and not part of the main solution.

  • Nicholas

    Im using visual studio and whenever i try to run the exact same code you used for question 5 it comes up with 1>MSVCRTD.lib(exe_winmain.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
    1>c:\users\nick\documents\visual studio 2015\Projects\hello world\Debug\hello world.exe : fatal error LNK1120: 1 unresolved externals

    • Alex

      This should compile. It’s not clear to me what the problem might be. I’d try creating a new project, making sure you’re creating a Win32 console application, and see if it works.

  • Meredith

    This might have been said before but for questions 1 and 2 you have used cout without the namespace (the std::). Not a big deal I know, but could be considered as one of the mistakes you’re asking people to look for. Unless I’m missing something obvious?

    I am enjoying reading through this tutorial thus far. Thank you very much for it.

  • Tudor

    Hi all,
    I have to be honest and say that I’m really struggling with this section. I can’t understand why function parameters and arguments are necessary. And, since I don’t understand the purpose, I’m finding it difficult to understand the whole section. I’ve read the intro several times as well as reviewed the previous sections looking for a clue but I can’t see why you’d need to pass a value from main to a function. Can’t you just perform whatever calculation you need within the function body?

    • Alex

      > Can’t you just perform whatever calculation you need within the function body?

      For many things, yes. However, for non-trivial programs, having all your code in main() will get unmanageable.

      Functions have quite a few benefits:
      1) They break up your code into smaller pieces that can be managed.
      2) They allow you write reusable pieces of code that can be used multiple times (e.g. the getValueFromUser() example from the previous lesson -- we only had to write the code for getValueFromUser() once, and we used it twice).
      3) They abstract away the details of how something works. To use a function, you only need to understand its name, inputs, and outputs. You don’t need to know how it works internally. This is less important when you’re writing your own functions, but super nice when you’re using someone else’s functions (e.g. something from the standard library).

      Edit: I added a lesson 1.4b -- Why functions are useful, and how to use them effectively to address this point further.

  • @Tudor What I understand is that if you want to do the same calculation with different data, you can define a function with parameters(to catch the values passed by the caller) for that calculation and if the calculation is needed in multiple functions, all the different functions can pass value(arguments) to the calculator function to do the calculation with passed argument(s) and return the calculated value back to them. main() is not the only function that can call other functions. Any function can call any other function. I am also a newbie and not sure if am everywhere right.

    @Alex

    "Problem 2: multiply() calculates a value and puts the result in a variable, but never returns the value to the caller. Because there is no return statement, and the function is supposed to return an int, this will produce a compiler error."
    You wrote this in solution 2. I had a doubt on your statement("this will produce a compiler error"). To clear this,  I fixed one problem in that code by giving one more value(5) as argument when multiply() is called in main(e.g. multiply(4,5)). When I pasted the fixed code in Code::Blocks, the output it gave was shocking. It printed 20 on the console (that was not expected because there is no return expression in function multiply). I took that code and pasted in ideone.com (an online compiler). The code was compiled fine there and printed 0(confusion, why 0?). I don’t know what compiler they use. May be I am wrong but I think that code(when given one more value to match the parameter list) won’t give any compiler error in any case because when we do not write any return statement for a function and call it in other function, compiler doesn’t throw any error. I think you should recompile that code in your compiler/IDE. Whatever, The result that Code::Blocks gave is still confusing.

    • Alex

      It looks like some compilers don’t treat missing return statements for non-void functions as an error. The C++ spec doesn’t define what the behavior should be in this case, so the result could be anything. And as you see, the result was different in different compilers.

  • luca

    Thank you so much for this guide, really easy to understand. I was so suprised i got all the questions correct especially question 5 (slightly the long route ha).

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

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

    int main()
    {
        std::cout << "enter a number to multiply by 2";
        int x = 0;
        std::cin >> x;
        std::cout << "your value is"

            ; std::cout << multiply(x, 2) << std::endl;
        return 0;
    }

  • Tudor Reece

    Thanks for the help Alex and Avneet. Think I’m getting my head around it now. I apologize if the question was a bit obvious. Alex I have to say that as an absolute beginner with both C++ and programming in general, the tutorials are much better than anything else I’ve found so far. Thanks =)

  • Collin

    hey there i made the 5th question but different and gave me a doubled result is it better?:
    #include<iostream.h>
    int doubleNumber(int a)
    {
        cin>> a;
        return a * 2;
    }
    int main()
    {
        cout<< doubleNumber(3);
        return 0;
    }

  • Derek

    Another question about number 5. I wrote a program that completed the parameters, but is it too complicated for the task? mine seems much longer than yours. Thanks.

    • Alex

      No, this is great. 🙂 You’ve done a good job having each of your functions have one job, and using parameters and return values to move the data around.

  • Ben

    Ehm… You always say that if you’re using visual studio you should use #include "stdafx.h". But I’m using visual studio and #include "stdafx.h" didn’t work for me- Instead I have to use #include "stdfix.h". Why is that?

  • Sam

    Hey dude,

    Just working through your website, loving the tutorials so far.  Really easy to follow and the questions so far have been about right for difficulty.  Really looking forward to getting towards the end.

    Wanted to post my question 5 answer.  I actually did question 4, then wrote the program to just test out the function XD.  Then read question 5 like… oh that’s cool already done haha.

  • Joao Lopes

    Here is the code I did for exercise #5

  • Joao Lopes

    1More way of doing it, my question is: is there any difference?

  • Iamthatis

    How over complicated is my code for question 5 solution (after seeing so many doubleNumber() {return 2*x;} solutions)?

    • Alex

      Your code isn’t over-complicated, but it is structured a little strangely.

      If you didn’t know how doubleNumber() was implemented, would you expect it to take input from the user? Probably not. The function is also doing two things: getting input, and doubling it. That violates the functions should do one thing rule. You should probably split that function into two functions -- one to handle the input, and one to do the doubling.

      • Iamthatis

        I guess I more misunderstood the nature of functions. I was thinking of them almost as being small, independent programs that are combined to create more complex programs as opposed to being variables/aliases used to call individual tasks. Since doubleNumber() was supposed to double a value, I had it also ask for the value to double. Thanks for helping clear that up! 🙂

        • Alex

          Thinking about functions as small independent programs is actually a good metaphor. Personally, I like to think about functions as “building blocks”, like Legos, that you can combine to do more advanced things. The simpler and more focused on doing one thing well you can keep each individual function, the easier they will be to write, test, reuse, and combine.

          Consider your original function that asks the user for input AND doubles it. What if we wanted to print the user value doubled, and then doubled again? We couldn’t use your function twice, because we wouldn’t want to ask for input a second time. However, if we separated the input from the doubling, we could call the input function once, and the doubling function twice.

          Parameters exist to provide a way for the caller to provide inputs for a function to work with, so each function that needs to work with data doesn’t have to ask the user for it. This makes most of our functions _more_ independent, because now only the input functions need to have a dependence on user-entered data. The rest can just get input from the caller and calculate a value or print output without any dependence on the user.

          • Iamthatis

            So I THINK I finally get it. I used your example (double doubling) as practice, and came up with this:

        • Darren

          Another interpretation of functions (especially those you have not written yourself) is as a number crunching machine that takes inputs and gives an output (ignoring void functions and any side-effects). In well written code the name of the function tells the user what it does. For example,

          will initialise the floating point variable y with the sine of the input variable x (with x being previously initialised and representing an angle).  Input is x, it is processed according to the function definition, and the output or result is returned and given to y.

  • Joao Lopes

    Made another one I am so surprised how its possible to make the same thing in different ways amazing language Thanks for the awesome tutorial.

  • Jim

    Alex, Great Tutorials.
    I’ve never understood why they use the word argument in programming languages. Since you are not arguing about anything.  They should always be called Parameters in my opinion. Since you are passing parameters to a function and receive those same parameters from the caller. Can you argue about that? (Smile)

    • Alex

      I’ve never understand why they are called arguments either. Seems more like an agreement to me!

      Many people informally use the word parameter to refer to both the argument and the parameters in the function declaration. I find it’s useful to distinguish them, at least when trying to teach.

  • Jim

    Line 16 on quiz #3 is confusing. Since it’s easy to confuse the add parameters (x,y) with the multiply parameters with the same names. But they are entirely different. I would have written it like this to make it a little clearer.
    multiply((add(1,2,3)),4)
    But even this is confusing.

    Can’t this be done another way?

    • Alex

      Sure, you could break it into two lines, like this:

      Although this may be less efficient, in some cases it can be easier to understand.

  • Justine

    From question 4 and 5 this is my solution, what’s the difference of my solution to your example? any advantage/disadvantages?

    • Alex

      What you’re doing isn’t wrong in a logical sense, it just doesn’t answer the question the quiz asks. doubleNumber() is supposed to be a function that takes one integer parameter and returns double that value. Your function takes no parameters.

      From a purist standpoint, I’d say your function violates the “functions should do one thing” rule, as it asks the user for input AND doubles it. It would be better to separate those two things.

  • mohamed

    i did it that way

    #include "stdafx.h"
    #include <iostream>
    using namespace std;

    int main(int a)

    {
        cout << " please enter an integer ";

    cin >> a;
    cout << a << " x " << 2 << " = " << (a * 2);
    cin.clear();
    cin.ignore(32757, ‘\n’);
    cin.get();
    return 0;

  • sajjadhussain

    My question is why is it important to inisialize y as I already have wrote int y?

    • Alex

      “int y” just tells the compiler that you’re defining an integer variable named “y”. It doesn’t give that variable a value.

      In this case, since you’re asking the user to input the value of y immediately, you don’t really need to initialize y.

      But more generally, you’ll typically want to give your variables known values so they have predictable behavior.

  • Steven

    I might have overlooked this in previous less or it could be in a future lesson, but where would it be appropriate to use "void" rather than "int"? I understand that void does not return a value, and that using it as a main will not work, so is it only useful in functions that will be used in mains? (Sorry if I’m fumbling in my coding knowledge. Never coded before coming across these lessons, and throughout the week I’ve been going through and typing out and playing with the examples.)

    • Alex

      You should use void as the return type for any function that does not return a value to the caller. For example:

      This function takes an integer parameter and does not return anything back to the caller. Thus, the return type is void.

  • HitoShura

    thanks so much for these helpful tutorials they are a great help!
    You’ve earned my eternal gratitude Sir!

  • Miroslav

    Hello Alex, I am trying to make a simple game where you fight other countries and the battles are generated randomly. I think I have made a good function for the battle, but now I must make it repeat itself until you win. (For example if you win the first time you will not need to fight again, but every time you fail you must repeat the battle.) I tried using for like this :

    But it just skips the for. I don’t really know how to use for. The thing it should do is to start the battle once. Then every time it fails it should do it again. country_win is declared in the battle() as well. Here is the function:

    Thank you in advance.

    • Alex

      A do/while loop seems appropriate for this use case since you want to loop while a condition is true (the user has not won yet). We talk about different kinds of loops in chapter 5.

  • Stavros

    I’m trying to do the 5th quiz but i keep getting errors and I dont know why, I could use the info!
    3rd line expected unqualified id before ‘int’
    expected ‘)’ before ‘int’

  • lyndon

    Awesome tutorial
    heres my answer to question 5

    #include <iostream>

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

    int main()
    {
        std::cout << "Enter a Number: ";
        int x;
        std::cin >> x;
        std::cout << "your number doubled is " << doubleFx(x) << std::endl;
        return 0;
    }

  • LOL @Alex… You forgot to mention that if you use return instead of parameters or vice-versa it will result in an indefinite loop…We can use return and parameter as a pair but not return-return or parameter-parameter…I learnt it the hard way…Please mention it above for gods sake.But i can interchange return and parameter statement between two functions but not with main…Because main always returns 0…Correct me if I am wrong…I am new to functions so the above statement is a little vague

    • Alex

      Sorry, I’m not clear on what you mean. How would you use return instead of parameters or vice-versa?

      They serve different functions: parameters allow you to pass one or more values into the functions, return values let you pass a single value back to the caller.

      • [code]
        #include <iostream>
        int main(int);
        using namespace std;
        int bookmark()
        {
        int x;
        x=2;
        main(x);
        }
        int main(int y=0)
        {
            cout<<"aaa"<<y;     \\I could have written this line below the next line,Its just to see the working of
            bookmark();         \\my code
            return 0;
        }
        [\code]
        You see what I mean…If I forcefully try to use parameters instead of return to send values back to the main function…It becomes a loop…INEVITABLY.Now if you use parameter-parameter pair (lets say for sending and receiving multiple values)explicitly between two functions…If you manage to write a program like that you will see that it turns out to be a loop…So to solve that problem there needs to be one more function to compensate for the loop…Its hard to explain…Suppose there are two functions A,B…I can send multiple values from A to B with the help of parameters…Now I want to send multiple values from B to A…I cannot use return statement as it deals only with one value at a time….So ill make a new function C,Ill use parameters to send multiple values from B to C and then C to A…..I have not written this program till now…Its just an Idea…Better Ideas are appreciated…Thanx

        • Alex

          Aah, I see what you mean. Yes, in the program above, main() calls bookmark(), which calls main(), which calls bookmark(), infinitely. Because none of these functions ever terminate, the program will eventually consume all available stack memory and crash.

          The thing to note is that when bookmark() calls main(), it’s not sending a value back to main. It’s calling main() again with a new set of parameters.

          It is possible to have a function modify a value that the caller passed in by using what’s called a reference parameter. In the case above, this could be used to have bookmark() pass a value back to main(). This is covered in chapters 6 and 7.

  • PurpleKitty

    can I get a better description of why is cin>> used

    • Alex

      std::cin is an object representing console input. >> is an operator that (in this context) means get data from the console user and put it in whatever variable is to the right of the operator.

      So when we say “std::cin >> x”, we’re saying “get input from the console user, and put that input in variable x”.

  • redd3r

    Hello, I am wondering if the way I get input is acceptable or commonly used, I write a separate function for it. It seems unnecessary here but in larger programs I could see a benefit….or am i crazy?

    • Alex

      Totally fine, and in many cases, desirable (particularly for non-trivial programs, or programs where you need to get user input more than once).

      This also gives you a convenient place to do error handling. For example, what if the user doesn’t enter an integer? You’ll probably want to ask the user to try again. That error handling logic would be perfect to add to that getUserInput() function.

  • J. LaDove

    Even using your code solution (Code::Blocks 13.12), I keep getting this error when I run Problem 5:

    sh: 1: Syntax error: "(" unexpected

    Process returned 2 (0x2)  execution time : 0.003 s
    Press ENTER to continue.

    ---
    inxi: 1.9.17
    Client: Shell (zsh)
    Kernel: 3.16.0-38-generic i686 (32 bit) Distro: Linux Mint 17.2 Rafaela

    • Alex

      It seems like the program is trying to run in your shell, rather than get compiled by Code::Blocks. You should check your Code::Blocks config and make sure it’s set up to compile your programs with a C++ compiler rather than run them in your default shell.

  • Kawasukie

    • Kawasukie

      • Kawasukie

        • Alex

          In your previous program:

          Your above program is a better solution, but for reference you could have also done:

  • running-song

    I’m a novice of CPP,and the following is my doubt:
    you said "return 0"meant everything went OK,but then there were many "return x*y"、"return x+y" shown up, how could I tell the difference?

    • Alex

      When I say “return 0 meant everything went OK”, I’m only talking about the return value from main (which goes back to the operating system). The return value from other functions don’t have any implicit meanings.

  • pirate

    Hi Alex,
    Why cant this give the results wanted in question no. 5?

    It doesn’t double the integer input by user.

    • Alex

      Actually it does double the integer input by the user. But nothing is being done with the return value from doubleNumber(), so it is being discarded.

      You will either need to print the return value of doubleNumber (using std::cout):

      or temporarily store it in a variable and then print the variable:

  • Nyap

    Why does it still say “Process returned 0 (0x0)” when you execute your program, even when you don’t put return 0; at the end of the main function?

    • Alex

      Some compilers will assume you meant to return 0 if you forget to add a return statement to main. That’s likely what’s happening in this case.

  • moopet

    I wonder, why I get the error message "(21): error C2065: ‘x’: undeclared identifier"
    If I repeat

    at the beginning of the main function, I still get "(25): error C4700: uninitialized local variable ‘x’ used"
    I understand, what it tells me, but I initialized x, didn’t I?
    I thought, I only had to initialize x once. However, even if

    Here is my code

    • Alex

      It’s complaining about this line in main:

      You never declared variable x in the scope of function main.

      It looks like the previous line should be:

      That way you’ll have declared x in the scope of main and initialized it with the result returned from function getValueFromUser().

  • Mohamed

    Hi , I personally didn’t understand the importance of those arguments and parameters !! isn’t easier to do this :

    instead of this :

    Can anyone please explain me in the simplest way possible why do we really need those parameters and arguments ?? Pls help me !!
    Another thing , I’m afraid I didn’t completely understand what a return sentence is !! I know this is not the right place for that but pls explain that too .
    Thanks Alex A lot for this incredible website by the way !!

    • Alex

      Hi Mohamed,

      You’re right -- it is simpler to just do the addition directly than call a function to do it. But that’s missing the point. The point of the example is to show you the _mechanics_ of how function calls and function parameters work, using examples that are simple enough that you can easily understand what they are doing.

      The return statement of the function is used to allow a function to return a single value back to the caller of the function. In the case of function sum(), the function is returning the sum of the two parameters, which is then being passed to std::cout to be printed on the console.

  • Nyap

    So basically:

    a) Arguments are the values that are sent to the called function
    b) Parameters are the containers for the arguments
    c) Arguments can be digits, variables or function calls

    All I see scrolling down is examples which I can’t be bothered to read, have I missed anything?

  • hi,Alex

    i don’t understand the role of void function in c++ if it returns nothing at all ?

    thank you for providing such great tutorials !!

    • Alex

      Functions can be used for lots of things besides just calculating and returning values. Imagine a function that prints a list of names to the screen. This function probably doesn’t need to return anything to the caller, so it could be declared as returning void.

  • Big"B"LuvRRR

    Hey, how come

    only returns "original" value of x, 5, whereas using

    does indeed get x evaluated, with the desired value, 10, returned…???

    What’s going on , please?????

    • Alex

      Consider what happens when the top version of function doubleNumber() is called with x = 5.
      First, x * 2 is evaluated. This produces the result of 10. Because nothing is done with this evaluated value, it is discarded. Thus, x still has value 5. This function then returns 5.

      The bottom version of function doubleNumber() works as expected because after x * 2 is evaluated to value 10, that value of 10 is returned.

      You could fix the top version of function doubleNumber() by changing “x * 2” to “x = x * 2”, which is what you probably intended.

      • Big&amp;quot;B&amp;quot;LuvRRR

        Oh, wow…see, this is what’s so hard about programming for me -- while things often need to be spelled out micro-step-by-micro-step (such as "x = x * 2"), other times you can just combine things ("return x * 2")….

        Thanks a big ol’ bunch for the "think-through!"  I guess it’s a bit like learning English contractions, say -- which words can be contracted ("don’t," "can’t," etc.) and which ones probably cannot be ("tomorrow’ll be hot," "amn’t I clever" [well, this last one seems fine in "Irish English"]) -- I just gotta learn when things gotta be “spelled out” and when they can be “assumed” (“contracted”)…! 🙂

  • Alex

    My code was different for the last one but I’ve got the same result, just as you said.

  • Teo

    So i put in the following code in VC and it’s not working, everything before "int doublenumber" was there (except for

    ) when i just started the project, i didn’t know what it was so i just ignored it.

    Then i get 30 errors. One saying that "doublenumber(x) must declare a body" and another one states that "not all code paths return a value" and telling me that ) was expected in unusual places, can anyone help me?
    PS: It also tells me “Alias std not found” both when using as well as not using “using namespace std;”

    • Alex

      This looks like a C# program, not a C++ program. Make sure you’ve properly installed the Visual Studio C++ compiler, and that you’re creating a C++ project, not a C# project.

  • sarvesh

    thank you for C++ tutorials…very helpful for beginners like me

  • Tristan Gybels

    Can someone tell me why the console’s output is 00DC1384 instead of 5? And how to become 5 in a clean code

    • Alex

      You’re printing the address of the function rather than the return value of the function.

      Change:

      to

  • Khalifa

    it evaluates a value of 33 ,, my question is how can geta more accurate answer ( decimals ) ?

  • confus

    I don’t get question 4. No matter what I put in it just says ”fatal error LNK1120: 1 unresolved externals”

    Even if I literally just copy paste your code it says that.

  • Murlidhar

    #include "stdafx.h"
    #include <iostream>
    int getValuFromUser()
    {
        std::cout << "Enter An Integer: ";
        int x;
        std::cin >> x;
        return x;
    }
    int main()
    {
        int x = getValuFromUser();
        int y = x;
        int z = x + y;
            std::cout << x << "+" << y << "=" << z << std::endl;
        
        return 0;
    }

    Solution for Q.5. Is it a good idea? cause i dont knew how to use function (doubleNumber)
    Its working 100%.

  • Gustavo

  • Olvin Lizama

    Awesome Tutorials, here is my Answer for Quiz 4 and 5

    A bit different from your answer,

    Saludos,

  • Jouy

    My solution:

  • Emiliano

    Check my program!

  • i have tried using both return 2 * x and x + x but i keep getting a memory allocation number. my code looks like this

    • Alex

      The problem is this line:

      It should be:

      You want to call the function doubleNumber(), so you need the ().

  • ramin

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

    // This function has two integer parameters, one named x, and one named y
    // The values of x and y are passed in by the caller
    void printValues(int x, int y)
    {
        std::cout << x << std::endl;
        std::cout << y << std::endl;
    }

    int main()
    {
        printValues(6, 7); // This function call has two arguments, 6 and 7

        return 0;
    }

    this code print nothing in visual c++????

  • Made this when I was doing the Solution 4 only to realize I needed to do the whole thing in solution 5 anyhow :’D
    I guess it’s more in debth?? Dunno, just wanted to post it.

Leave a Comment

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