In the last chapter, we defined a function as a collection of statements that execute sequentially. While that is certainly true, that definition doesn’t provide much insight into why functions are useful. Let’s update our definition: A function is a reusable sequence of statements designed to do a particular job.
You already know that every program must have a function named main (which is where the program starts execution when it is run). However, as programs start to get longer and longer, putting all the code inside the main function becomes increasingly hard to manage. Functions provide a way for us to split our programs into small, modular chunks that are easier to organize, test, and use. Most programs use many functions. The C++ standard library comes with plenty of already-written functions for you to use -- however, it’s just as common to write your own. Functions that you write yourself are called user-defined functions.
Consider a case that might occur in real life: you’re 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 the place you bookmarked and continue your book precisely where you left off.
C++ programs can 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 ends, the CPU returns back to the point it bookmarked, and resumes execution.
The function initiating the function call is called the caller, and the function being called is the callee or called function.
An example of a user-defined function
First, let’s start with the most basic syntax to define a user defined function. For this lesson, all user-defined functions (except main) will take the following form:
void identifier() // identifier replaced with the name of your function { // Your code here }
We’ll talk more about the different parts of this syntax in the next few lessons. For now, identifier will simply be replaced with the name of your user-defined function. The curly braces and statements in between are called the function body.
Here is a sample program that shows how a new function is defined and called:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> // for std::cout // Definition of user-defined function doPrint() void doPrint() // doPrint() is the called function in this example { std::cout << "In doPrint()\n"; } // Definition of function main() int main() { std::cout << "Starting main()\n"; doPrint(); // Interrupt main() by making a function call to doPrint(). main() is the caller. std::cout << "Ending main()\n"; // this statement is executed after doPrint() ends return 0; } |
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. We call function doPrint by appending a pair of parenthesis to the function name like such: doPrint()
. Note that if you forget the parenthesis, your program may not compile (and if it does, the function will not be called).
Warning
Don’t forget to include parenthesis () after the function’s name when making a function call.
Because a function call was made, execution of statements in main is suspended, and execution jumps to the top of called function doPrint. The first (and only) line in doPrint prints In doPrint()
. When doPrint terminates, execution returns back to the caller (function main) and resumes from the point where it left off. Consequently, the next statement executed in main prints Ending main()
.
Calling functions more than once
One useful thing about functions is that they can be called more than once. Here’s a program that demonstrates this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> // for std::cout void doPrint() { std::cout << "In doPrint()\n"; } // Definition of function main() int main() { std::cout << "Starting main()\n"; doPrint(); // doPrint() called for the first time doPrint(); // doPrint() called for the second time std::cout << "Ending main()\n"; return 0; } |
This program produces the following output:
Starting main() In doPrint() In doPrint() Ending main()
Since doPrint gets called twice by main, doPrint executes twice, and In doPrint() gets printed twice (once for each call).
Functions calling functions calling functions
You’ve already seen that function main can call another function (such as function doPrint in the example above). Any function can call any other function. In the following program, function main calls function doA, which calls function doB:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> // for std::cout void doB() { std::cout << "In doB()\n"; } void doA() { std::cout << "Starting doA()\n"; doB(); std::cout << "Ending doA()\n"; } // Definition of function main() int main() { std::cout << "Starting main()\n"; doA(); std::cout << "Ending main()\n"; return 0; } |
This program produces the following output:
Starting main() Starting doA() In doB() Ending doA() Ending main()
Nested functions are not supported
Unlike some other programming languages, in C++, functions cannot be defined inside other functions. The following program is not legal:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> int main() { int foo() // Illegal: this function is nested inside function main() { std::cout << "foo!"; return 0; } foo(); // function call to foo() return 0; } |
The proper way to write the above program is:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> int foo() // no longer inside of main() { std::cout << "foo!"; return 0; } int main() { foo(); return 0; } |
Quiz time
Question #1
In a function definition, what are the curly braces and statements in-between called?
Question #2
What does the following program print? Do not compile this program, just trace the code yourself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> // for std::cout void doB() { std::cout << "In doB()\n"; } void doA() { std::cout << "In doA()\n"; doB(); } // Definition of function main() int main() { std::cout << "Starting main()\n"; doA(); doB(); std::cout << "Ending main()\n"; return 0; } |
![]() |
![]() |
![]() |
why do i need to put "endl" at the end of somethings? It tells me too but when i dont it still works.
In these examples, endl moves the cursor to the next line.
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 .
Hello, Andrew
doprint() serves no purpose here.
This would be easier to read and write.
when I click build it says it "succeeded" but it doesnt open up the run window to show it. What is wrong?
You have to execute/run the program after building it.
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 ?
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.
I already know Javascript and some normal Java but this is not responding to things like 'cin' and 'end1' in the 'iostream' library. Why?
Part of the problem may be because it's endl and not end1 (end-ell and not end-one)
Do you always have to put all your functions above the main function?
For now, that's easiest. Later on in these tutorials, you'll learn ways to get around this restriction.
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
Red letters are correct.
i have tried the following example in the tutorial but it just doesn't work., What have missed?
The code is alright, so it must be something with your IDE
If you are NOT using Visual Studio, remember to remove stdafx
does cout mean ecout like in French
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
Very well explained thanks for these tutorials:) Here is my first program using functions.
Hi Alex,
Just wanted to add my thanks for a great tutorial.
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:
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;
}
Mike, it should be endl (end-L), not end1 (end-one), that is probably where the problem is!
is it normal for my ms-dos window to close right after i put in a number and press enter
Normally yes, unless you include a pause statement. Alex pointed out earlier that this is discussed in section 0.7.
Dude, just declare
before the functions! It works for me. Thanks :)
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.
What is the System("pause") in the above code ?
It causes the operating system to run an application named "pause", which has the effect of pausing for user input.
It works on some operating systems, but isn't recommended.
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.
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.
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?
Make sure you do the following at the top of your file (below the stdafx line):
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.
Hmmm, looks like you've *taken out* quizzes, too -- from this lesson, anyway! Folks seem to refer to quizzes here that are no longer available...what's happened to 'em, please??? Can be rather confusing reading comments when they refer to things no longer on the webpage....
What actually happened was that the lesson was getting too long, so I split it into two parts. The quiz moved into the second part. When I split a lesson, I'll try to match the comments with the correct part of the lesson, but it isn't always possible.
Thank you so much. This tutorial is definitely the best out there!
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 !=
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.
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;
}
________________________________________________
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
There is no <> operator in C++, so I'm not sure what you're attempting to do here.
Also i think x and y are not declared !!
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.
You actually can have two functions in C++ that call each other. However, to do this, you have to use function prototypes, which we I haven't covered at this point in the tutorials. I cover this in section 1.7 -- forward declarations
what is the difference between the following declarations
void show()and void show(void)
There is no difference. They are functionally equivalent.
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.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..
The problem is that you have a semicolon after
Remove the semicolon and it should work as expected.
Fox is right :)
These tutorials are fantastic :]
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.
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
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).
Hi Alex,
Thank you very much for this website which is no doubt best in the world for learning C++.
I have a question about std::cout, when I run this code it print 0 as well.
#include "stdafx.h"
#include <iostream>
int Hello()
{
std::cout<<"Hello World"<<std::endl;
return 0;
}
int main ()
{
std::cout<<Hello();
return 0;
}
I know that if I dont call the function Hello() in cout it wont print the returned 0, but any other solution.
Thank you
does two things:
1) It calls the Hello() function.
2) It prints the return value from the Hello() function.
The Hello() function prints the string "Hello World", and then it returns the value 0, which main() prints.
There are two things you should change:
1) Function Hello() should not have a return type of int (it should have a return type of void, since this function does not need to return anything to the caller).
2) Function main() should not print the return value of Hello(). A simple call to Hello() will suffice.
#include <iostream>
int dprint(){
std::cout<<"welcome to he menu"<<std::endl;
return 0;
}
int main() {
std::cout<<"print the menu"<<std::endl;
dprint();
std::cout<<"end of menu";
// your code goes here
return 0;
}
This code did not print 0 as mentioned by above fellow Nd as explained by you. What's wrong in it plz tell.
dprint() is returning value 0, but you're not doing anything with this value, so it's discarded. You probably meant:
Thanx this was new :)