Functions
A C++ program is constructed from building blocks called
functions. A
function is a subroutine that contains one or more C++ statements and
performs one or more tasks. In well-written C++ code, each function
performs only one task. Each function has a name, and it is this name
that is used to call the function. In general, you can give a
function whatever name you please. However, remember that main(
) is reserved for the function that begins
execution of your program. In C++, one function cannot be embedded
within another function. Unlike Pascal, Modula-2, and some other
programming languages that allow the nesting of functions, C++
considers all functions to be separate entities. (Of course, one
function may call another.) When denoting functions in text, this
book uses a convention that has become common when writing about C++:
A function will have parentheses after its name. For example, if a
function’s name is getval,
then it will be written getval
( ) when its name is used in a sentence. This
notation will help you distinguish variable names from function names
in this book. In your first programs, main
( ) was the only function. As stated earlier,
main ( ) is
the first function executed when your program begins to run, and it
must be included in all C++ programs. There are two types of
functions that will be used by your programs. The first type is
written by you. Main (
) is an example of this type of function. The
other type of function is implemented by the compiler and is found in
the compiler’sstandard
library. (The standard library is discussed
shortly, but in general terms, it is a collection of predefined
functions.) Programs that you write will usually contain a mix of
functions that you create and those supplied by the compiler. Since
functions form the foundation of C++, let’s take a closer look at
them now.
A Program with Two Functions
The following program contains two functions: main
( ) and myfunc
( ). Before running this program (or reading
the description that follows), examine it closely and try to figure
out exactly what it displays on the screen.
/* This program contains two functions: main ()
and myfunc().
*/
#include <iostream>
using namespace std;
void myfunc(); // myfunc's prototype
int main()
{
cout << "In main()";
myfunc(); // call myfunc()
cout << "Back in main()";
return 0;
}
void myfunc()
{
cout << " Inside myfunc() ";
}
The program works like this. First, main(
) begins, and it executes the first cout
statement. Next, main(
) calls myfunc(
). Notice how this is achieved: the
function’s name,
myfunc,
appears, followed by parentheses, and finally by a semicolon.
A function call is a C++ statement and,
therefore, must end with a semicolon. Next,
myfunc( ) executes its cout
statement, and then returns to main(
) at the line
of code immediately following the call.
Finally, main( )
executes its second cout
statement, and then terminates. The output on
the screen is this: In
main() Inside myfunc() Back in main()
There is one other important statement in the
preceding program: void
myfunc(); // myfunc's prototype As the comment
states, this is the prototype
for myfunc(
). Although we will
discuss prototypes in detail later, a few words
are necessary now. A function
prototype declares the
function prior to its definition. The prototype allows the compiler
to know the function's return
type, as well as the number and type of any parameters that the
function may have. The compiler needs to know
this information prior to the first
time the function is called. This is why the
prototype occurs before main(
). The only
function that does not require a prototype is
main( ),
because it is predefined by C++.
As you can see, myfunc(
) does not contain a return
statement. The keyword void,
which precedes both the prototype for myfunc(
) and its definition, formally states
that myfunc(
) does not return a value. In C++,
functions that don’t return values
are declared as void.
FUNCTIONS
what is a function?
what is a function?
A function is a structure that has a number of program statements
grouped as a unit with a name given to the unit. Function can be
invoked from any part of the C++ program.
Features of Function:
To understand why the program structure is written separately and
given a name, the programmer must have a clear idea of the features
and benefits of function. This will encourage better understanding of
function usage:
- Use of Functions gives a Structured Programming Approach
- Reduces Program Size:
The piece of code that needs to be executed, or the piece of code
that is repeated in different parts of the program, can be written
separately as a function and stored in a place in memory. Whenever
and wherever needed, the programmer can invoke the function and use
the code to be executed. Thus, the program size is reduced.
Having known about the function and its features let us see how to
declare, define and call a function
in a C++ program.
Declaring a Function:
It has been discussed that, in order for a variable to be used, it
must be declared. Just like variables, it follows that function
definitions must be declared. The general method of declaring a
function is to declare the function in the beginning of the program.
The general format for declaring a function is
Return_datatype function name (arguments);
Suppose we have a function named as item which returns nothing from
the function it is declared as
Void item ( );
This declared would inform the compiler that the presence of the
function item is there in the program. In the above the return type
void tells the compiler that the function has no return value and
also the empty braces ( ) indicate that the function takes no
arguments.
Defining a function:
The definition is the place where the actual function program
statements or in other words the program code is placed.
The general format of the function definition is as follows:
Return_datatype function name (arguments)
//Declaratory
{
program statements //Function Body
……..
……….
}
{
program statements //Function Body
……..
……….
}
In the above the declaratory must match the function declaration
already made. That is the function name, the return type and the
number of arguments all must be same as the function declaration
made. In fact if arguments are declared and defined. The order
of arguments defined here must match the order declared in the
function declaration.
After the declaratory the braces starts and the function body is
placed. The function body has the set of program statements which are
to be executed by the function. Then the function definition ends
with} ending braces.
For example let us see how to define a function item declared as
void that prints first five integers.
void item( )
{
int i;
for (i=1;i<=5;i++)
cout<< i;
}
{
int i;
for (i=1;i<=5;i++)
cout<< i;
}
The output of the function when it is called would be
12345
Calling the function:
The function must be called for it to get executed. This process is
performed by calling the function wherever required.
The general format for making the function call would be as follows:
Function name ();
When the function is called the control, transfers to the function
and all the statements present in the function definition gets
executed and after which the control, returns back to the statement
following the function call.
In the above example when the programmer executes the function item,
he can call the function in main as follows:
item ();
Let us see a complete program in C++ to help the programmer to
understand the function concepts described above:
#include
void main ( )
{
void item( ); //Function Declaration
item( ); //Function Called
cout<<”\n End of Program”;
}
void main ( )
{
void item( ); //Function Declaration
item( ); //Function Called
cout<<”\n End of Program”;
}
Void item ( ) //Function Definition
{
int i;
for(i=1;i<=5;i++)
cout<< i;
}
{
int i;
for(i=1;i<=5;i++)
cout<< i;
}
The output of the above program is
12345
End of Program
Function Arguments
It is possible to pass one or more values to a function.
A value passed to a function is called an argument.
In the programs that you have studied so far,
none of the functions take any arguments. Specifically, neither main(
) nor myfunc(
) in the preceding examples have an argument.
However, functions in C++ can have one or more arguments. The upper
limit is determined by the compiler you are using, but Standard C++
specifies that at least 256 arguments will be allowed. Here is a
short program that uses one of C++’s standard library (i.e.,
built-in) functions, called abs(
), to display the absolute value of a number.
The abs( ) function
takes one argument, converts it into its absolute value, and returns
the result.
//
Use the abs() function.
#include
<iostream>
#include
<cstdlib>
using
namespace std;
int
main()
{
cout
<< abs(-10);
return
0;
}
Here, the value –10 is passed as an argument to abs(
). The abs(
) function receives the argument that it is
called with and returns its absolute value, which is 10 in this case.
Although abs( ) takes
only one argument, other functions can have several. The key point
here is that when a function requires an argument, it is passed by
specifying it between the parentheses that follow the function’s
name.
The return value of abs(
) is used by the cout
statement to display the absolute value of
–10 on the screen. The reason this works is that whenever a
function is part of a larger expression, it is automatically called
so that its return value can be obtained. In this case, the return
value of abs( ) becomes
the value of the right side of the <<
operator, and is therefore displayed on the
screen. Notice one other thing about the preceding program: it also
includes the header <cstdlib>.
This is the header required by abs(
). In general, whenever you use a library
function, you must include its header. The header provides the
prototype for the library function, among other things. When you
create a function that takes one or more arguments, the variables
that will receive those arguments must also be declared. These
variables are called the parameters
of the function. For example, the function
shown next prints the product of the two integer arguments passed to
the function when it is called.
void
mul(int x, int y)
{
cout
<< x * y << " ";
}
Each time mul(
) is called, it will multiply the value
passed to x by
the value passed to y.
Remember, however, that x
and y
are simply the operational variables that
receive the values you use when calling the function. Consider the
following short program, which illustrates how to call mul(
):
//
A simple program that demonstrates mul().
#include
<iostream>
using
namespace std;
void
mul(int x, int y); // mul()'s prototype
int
main()
{
mul(10,
20);
mul(5,
6);
mul(8,
9);
return
0;
}
void
mul(int x, int y)
{
cout
<< x * y << " ";
}
This program will print 200, 30, and 72 on the screen.
When mul( ) is
called, the C++ compiler copies the value of each argument into the
matching parameter. That is, in the first call to mul(
), 10 is copied into x
and 20 is copied into y.
In the second call, 5 is copied into x
and 6 into y.
In the third call, 8 is copied into x
and 9 into y.
If you have never worked with a language that allows parameterized
functions, then the preceding process may seem a bit strange. Don’t
worry; as you see more examples of C++ programs, the concept of
arguments, parameters, and functions will become clear.
REMEMBER:
The term argument
refers
to the value that is used to call a function. The variable that
receives the value of an argument is called a parameter.
In fact, functions that take arguments are called parameterized
functions. In C++ functions, when there are two or more arguments,
they are separated by commas. In this book, the term argument
list refers
to comma-separated arguments. The argument list for mul(
) is
x,y.
Functions Returning Values
Many of the C++ library functions that you use will
return values. For example, the abs(
) function used earlier returned the absolute
value of its argument. Functions you write may also return values to
the calling routine. In C++, a function uses a return
statement to return a value. The general form
of return is
return value;
where value is
the value being returned. To illustrate the process of functions
returning values, the foregoing program can be rewritten, as shown
next. In this version, mul(
) returns the product of its arguments.
Notice that the placement of the function on the right side of an
assignment statement
assigns the return value to a variable.
//
Returning a value.
#include
<iostream>
using
namespace std;
int
mul(int x, int y); // mul()'s prototype
int
main()
{
int
answer;
answer
= mul(10, 11); // assign return value
cout
<< "The answer is " << answer;
return
0;
}
//
This function returns a value.
int
mul(int x, int y)
{
return
x * y; // return product of x and y
}
In this example, mul(
) returns the value of x*y
by using the return
statement. This value is then assigned to
answer.
That is, the value returned by the return
statement becomes mul(
)'s value in the calling routine. Since mul(
) now returns a value, it is not preceded by
the keyword void.
(Remember, void is
used only when a function does not
return a value.) Just as there are different
types of variables, there are also different types of return values.
Here, mul( ) returns
an integer. The return type of a function precedes its name in both
its prototype and its definition. Before moving on, a short
historical note is in order. For early versions of C++, if no return
type is specified, then a function is assumed to return an integer
value. For example, in old code you might find mul(
) written like this: //
An old-style way to code mul(). mul(int
x, int y) // default to int return type
{
return
x * y; // return product of x and y
}
Here, the type returned by mul(
) is integer by default, since no other
return type is specified. However, the "default-to-int"
rule was dropped by Standard C++. Although most compilers will
continue to support the "default-to-int" rule for the sake
of backward compatibility, you should explicitly specify the return
type of every function that you write. Since older code frequently
made use of the default integer return type, this change is also
something to keep in mind when working on legacy code. When a return
statement is encountered, the function
returns immediately, skipping any remaining code. It is possible to
cause a function to return by using the return
statement without any value attached to it, but this form of return
can be used only with functions that have no
return values and that are declared as void.
Also, there can be more than one return
in a function.
The main( ) Function
As you know, the main(
) function is special because it is the first
function called when your program executes. It signifies the
beginning of your program. Unlike some programming languages that
always begin execution at the "top" of the program, C++
begins every program with a call to the main(
) function, no matter where that function is
located in the program. (However, it is common for main(
) to be the first function in your program so
that it can be easily found.) There can be only one main(
) in a program. If you try to include more
than one, your program will not know where to begin execution.
Actually, most compilers will catch this type of error and report it.
As mentioned earlier, since main(
) is spredefined by C++, it does not require
a prototype.
The General Form of C++ Functions
The preceding examples have shown some specific types of
functions. However, all C++ functions share a common form, which is
shown here: return-type
function-name(parameter
list) {.. body
of the function.
}
Let’s look closely at the different parts that make up
a function. The return type of a function determines the type of data
that the function will return. As you will see later in this book,
you can specify nearly any return type you like. Keep in mind,
however, that no function has to return a value. If it does not
return a value, its return type is void.
But if it does return a value, that value must be of a type that is
compatible with the function’s return type. Every function must
have a name. After the name is a parenthesized parameter list. The
parameter list
specifies the names and types of variables
that will be passed information. If a function has no parameters, the
parentheses are empty. Next, braces surround the body of the
function. The body of the function is composed of the C++ statements
that define what the function does. The function terminates and
returns to the calling procedure when the closing curly brace is
reached or when a return
statement is encountered.
Some Output Options
Up to this point, there has been no occasion to advance
output to the next line—that is, to execute a carriage
return-linefeed sequence. However, the need for this will arise very
soon. In C++, the carriage return-linefeed sequence is generated
using the newline
character. To put a newline character into a string, use this code:
\n (a
backslash followed by a lowercase n). To see an example of a carriage
return-linefeed sequence, try the following program:
/*
This program demonstrates the \n code, which
generates
a new line.
*/
#include
<iostream>
using
namespace std;
int
main()
{
cout
<< "one\n";
cout
<< "two\n";
cout
<< "three";
cout
<< "four";
return
0;
}
This program produces the following output:
one
two
threefour
: The
newline character can be placed anywhere in the string, not just at
the end. You might want to try experimenting with the newline
character now, just to make sure you understand exactly what it does.
Inline functions
C++ Inline Functions
In
this C++ tutorial, you will learn about Inline function, what is
inlinfunction, reason for the need of inline function, what happens
when an inline function is written, general format of inline function
explained with example.
What is Inline Function?
Inline functions are
functions where the call is made to inline functions. The actual code
then gets placed in the calling program.
Reason for the need of Inline Function:
Normally, a function
call transfers the control from the calling program to the function
and after the execution of the program returns the control back to
the calling program after the function call. These concepts of
function saved program space and memory space are used because the
function is stored only in one place and is only executed when it is
called. This concept of function execution may be time consuming
since the registers and other processes must be saved before the
function gets called.
The extra time needed
and the process of saving is valid for larger functions. If the
function is short, the programmer may wish to place the code of the
function in the calling program in order for it to be executed. This
type of function is best handled by the inline function. In this
situation, the programmer may be wondering “why not write the short
code repeatedly inside the program wherever needed instead of going
for inline function?” Although this could accomplish the task, the
problem lies in the loss of clarity of the program. If the programmer
repeats the same code many times, there will be a loss of clarity in
the program. The alternative approach is to allow inline functions to
achieve the same purpose, with the concept of functions.
What happens when an inline function is written?
The inline function
takes the format as a normal function but when it is compiled it is
compiled as inline code. The function is placed separately as inline
function, thus adding readability to the source program. When the
program is compiled, the code present in function body is replaced in
the place of function call.
General Format of inline Function:
The general format of
inline function is as follows:
Inline
datatype function name (arguments)
The
keyword inline specified in the above example, designates the
function as inline function. For example, if a programmer wishes to
have a function named item with return value as integer and with no
arguments as inline it is written as follows:
inline
int item( )
Example:
The concept of inline
functions:
#include <iostream.h> int item(int); void main( ) { int x; cout << “\n Enter the Input Value: ”; cin>>x; cout<<”\n The Output is: “ << item(x); }
inline
int item(int x1)
{ return 5*x1; } |
The output of the above
program is:
Enter the Input Value:
10
The Output is: 50
The Output is: 50
The
output would be the same even when the inline function is written
solely as a function. The concept, however, is different. When the
program is compiled, the code present in the inline function item( )
is replaced in the place of function call in the calling program. The
concept of inline function is used in this example because the
function is a small line of code.
The above example, when
compiled, would have the structure as follows:
#include <iostream.h> int item(int); void main( ) { int x; cout << “\n Enter the Input Value: ”; cin>>x;//The item(x) gets replaced with code return 5*x1;cout<<”\n The Output is: “ << item(x); } |
When the above program
is written as normal function the compiled code would look like
below:
#include <iostream.h> int item(int); void main( ) { int x; cout << “\n Enter the Input Value: ”; cin>>x;//Call is made to the function itemcout<<”\n The Output is: “ << item(x); }
int
item(int x1)
{ return 5*x1; } |
A programmer must make wise choices when to use inline
functions. Inline functions will save time and are useful if the
function is very small. If the function is large, use of inline
functions must be avoided.
Static data members
The
properties of a static variable are similar to that of c static
variable.
Its
characteristics are:
*it
is initialized to zero when the first object of its class is created.
No other initialization is permitted.
*only
one copy of that member is created for the entire class and is shared
by all the objects, no matter how many objects are created.
It
is visible only within class, but its lifetime is the entire program.
- These are also known as class variables.
//write
a program for static data member
#include<iostream.h>
#include<conio.h>
class
abc
{
static
int x;
int
n;
public:
void
get(int d)
{
n=d;
x++;
}
static
void count()
{
cout<<x<<"\n";
}
};
int
abc::x;
int
main()
{
abc
a,b,c;
a.count();
//clrscr();
a.get(4);
b.get(6);
c.get(7);
a.count();
getch();
return
0;
}the
output is:
0
3
3
Static
member?
Friend function
Need
for Friend Function:
A
function that is not a member or an external class will not be able
to access the private data. A programmer may have a situation where
he or she would need to access private data from non-member functions
and external classes. For handling such cases, the concept of Friend
functions is a useful tool.
What is a Friend Function?
A friend function is
used for accessing the non-public members of a class. A class can
allow non-member functions and other classes to access its own
private data, by making them friends. Thus, a friend function is an
ordinary function or a member of another class.
How
to define and use Friend Function in C++:
The friend function is written as any other normal
function, except the function declaration of these functions is
preceded with the keyword friend. The friend function must have the
class to which it is declared as friend passed to it in argument.
Some
important points to note while using friend functions in C++:
- The keyword friend is placed only in the function declaration of the friend function and not in the function definition.
- It is possible to declare a function as friend in any number of classes.
. - When a class is declared as a friend, the friend class has access to the private data of the class that made this a friend.
. - A friend function, even though it is not a member function, would have the rights to access the private members of the class.
. - It is possible to declare the friend function as either private or public.
. - The function can be invoked without the use of an object. The friend function has its argument as objects.
No comments:
Post a Comment