Using functions in C++

By: Emiley J Emailed: 1598 times Printed: 2051 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

While main() is a function, it is an unusual one. Typical functions are called, or invoked, during the course of your program. A program is executed line by line in the order it appears in your source code, until a function is reached. Then the program branches off to execute the function. When the function finishes, it returns control to the line of code immediately following the call to the function.

A good analogy for this is sharpening your pencil. If you are drawing a picture, and your pencil breaks, you might stop drawing, go sharpen the pencil, and then return to what you were doing. When a program needs a service performed, it can call a function to perform the service and then pick up where it left off when the function is finished running. Listing below demonstrates this idea.

Demonstrating a call to a function.

1:     #include <iostream.h>
3:     // function Demonstration Function
4:     // prints out a useful message
5:     void DemonstrationFunction()
6:     {
7:         cout << "In Demonstration Function\n";
8:     }
10:    // function main - prints out a message, then
11:    // calls DemonstrationFunction, then prints out
12:    // a second message.
13:    int main()
14:    {
15:        cout << "In main\n" ;
16:        DemonstrationFunction();
17:        cout << "Back in main\n";
18:         return 0;
19: }
In main
In Demonstration Function
Back in main

The function DemonstrationFunction() is defined on lines 5-7. When it is called, it prints a message to the screen and then returns.

Line 13 is the beginning of the actual program. On line 15, main() prints out a message saying it is in main(). After printing the message, line 16 calls DemonstrationFunction(). This call causes the commands in DemonstrationFunction() to execute. In this case, the entire function consists of the code on line 7, which prints another message. When DemonstrationFunction() completes (line 8), it returns back to where it was called from. In this case the program returns to line 17, where main() prints its final line.

Using Functions

Functions either return a value or they return void, meaning they return nothing. A function that adds two integers might return the sum, and thus would be defined to return an integer value. A function that just prints a message has nothing to return and would be declared to return void.

Functions consist of a header and a body. The header consists, in turn, of the return type, the function name, and the parameters to that function. The parameters to a function allow values to be passed into the function. Thus, if the function were to add two numbers, the numbers would be the parameters to the function. Here's a typical function header:

int Sum(int a, int b)

A parameter is a declaration of what type of value will be passed in; the actual value passed in by the calling function is called the argument. Many programmers use these two terms, parameters and arguments, as synonyms. Others are careful about the technical distinction. This book will use the terms interchangeably.

The body of a function consists of an opening brace, zero or more statements, and a closing brace. The statements constitute the work of the function. A function may return a value, using a return statement. This statement will also cause the function to exit. If you don't put a return statement into your function, it will automatically return void at the end of the function. The value returned must be of the type declared in the function header.

Listing below demonstrates a function that takes two integer parameters and returns an integer value.

FUNC.CPP demonstrates a simple function.

1:    #include <iostream.h>
2:    int Add (int x, int y)
3:    {
5:      cout << "In Add(), received " << x << " and " << y << "\n";
6:      return (x+y);
7:    }
9:    int main()
10:    {
11:         cout << "I'm in main()!\n";
12:         int a, b, c;
13:         cout << "Enter two numbers: ";
14:         cin >> a;
15:         cin >> b;
16:         cout << "\nCalling Add()\n";
17:         c=Add(a,b);
18:         cout << "\nBack in main().\n";
19:         cout << "c was set to " << c;
20:         cout << "\nExiting...\n\n";
21:         return 0;
22: }

I'm in main()!
Enter two numbers: 3 5

Calling Add()
In Add(), received 3 and 5

Back in main().
c was set to 8


The function Add() is defined on line 2. It takes two integer parameters and returns an integer value. The program itself begins on line 9 and on line 11, where it prints a message. The program prompts the user for two numbers (lines 13 to 15). The user types each number, separated by a space, and then presses the Enter key. main() passes the two numbers typed in by the user as arguments to the Add() function on line 17.

Processing branches to the Add() function, which starts on line 2. The parameters a and b are printed and then added together. The result is returned on line 6, and the function returns.

In lines 14 and 15, the cin object is used to obtain a number for the variables a and b, and cout is used to write the values to the screen. Variables and other aspects of this program are explored in depth in the next few days.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

i m very glad to know and use this site. this is wonderful site for beginner in c++

View Tutorial          By: Rupinder at 2009-09-08 08:49:23
2. View Comment

me too

View Tutorial          By: bellyjoy at 2010-05-07 03:14:14
3. View Comment

programming is really exciting specially with c++^_^.

View Tutorial          By: Jully at 2010-07-28 18:42:23
4. View Comment

i m a student of Bahria university,Pakistan.and this site really helpful for us to learning the basic of C++.

View Tutorial          By: Rao Waseem at 2011-05-14 12:55:53
5. View Comment

... it is nice site coz 8 can help students lyk me.. to know further in c programming....... @.@

View Tutorial          By: mayflor at 2011-06-29 03:57:51
6. View Comment

its a nice site bcoz it gives a bright IDEA about C++

View Tutorial          By: surya santhan at 2012-07-11 16:28:06

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Emiley J
Password must include both numeric and alphabetic characters - Magento
What is Hadoop?
Returning multiple values from a web service
Tomcat and httpd configured in port 8080 and 80
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
How to Deploy a Java Web Service
Call a webservice in Java
Java WebService - Create your first web service in Java
package javax.jws does not exist
Getting Started with Android
HTML5 Location - getCurrentPosition() in HTML5
HTML5 Canvas - Using Canvas in HTML5
HTML5 - Introduction
HTML5 Video - Handling video in HTML5

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
A Brief History of C++
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
Getting Started with C++
Using functions in C++
The if Statement in C++
Using switch Statements in C++
The Stack and the Free Store in C++
assert() example program in C++
Using cout in C++
Using Comments in a C++ Program
How to use Enumerated constants in C++
Demonstration of Prefix and Postfix operators in C++
Advanced if Statements in C++
Use of Conditional (Ternary) Operator in C++
Most Emailed Articles (in C++)
The Stack and the Free Store in C++
Constructors and Destructors in C++
Nested Loops in C++
Getting User Input Using cin in C++
Programming errors a compiler will detect in C++
C++ keywords
Calculating total based on the given quantity and price in C++
Use of Conditional (Ternary) Operator in C++
Specifying default values to function parameters in C++
Tutorial on Classes and Members in C++
const Member Functions in C++
Classes with Other Classes as Member Data in C++
Looping with the keyword goto in C++
for Loops in C++
Dot (.) vs Arrow (->) to access data members in C++