Anda di halaman 1dari 30

COMPUTER SKILL 2

Edition 2 2014

Unit Seven
Function

Introduction
A function is an assignment or a task that must be performed to complement the other
part(s) of a program. There are two kinds of functions: those supplied to you and those
you will be writing. The functions that are supplied to you are usually in three categories:
those built-in the operating system, those written in C++ (they are part of the C++
language), and those supplied with your programming environment. The use of these
functions is the same regardless of the means you get them; you should know what a
function looks like, how to create one, what functions are already available, where they
are located, and what a particular function does, how and when to use it.

Functions allow to structure programs in segments of code to perform individual tasks. In C++,
a function is a group of statements that is given a name, and which can be called from some
point of the program.

Syntax of Function
The most common syntax to define a function is:

return-type function-name (parameters)


{
// function-body
}

Chapter Seven: Function [Type here] Page 1 of 30


return-type: suggests what the function will return. It can be int, char, some
pointer or even a class object. There can be functions, which does not return
anything, they are mentioned with void.
Function Name: is the name of the function, using the function name it is called.
Parameters: are variables to hold values of arguments passed while function is
called. A function may or may not contain parameter list. Parameters (as many as
needed). Each parameter consists of a type followed by an identifier, with each
parameter being separated from the next by a comma. Each parameter looks very
much like a regular variable declaration (for example: int x), and in fact acts
within the function as a regular variable which is local to the function. The
purpose of parameters is to allow passing arguments to the function from the
location where it is called from.
Function's body: is a block of statements surrounded by braces { } that specify what the
function actually does.

Example 1:

// function example
#include <iostream>
using namespace std;
1
2 int addition (int a, int b)
3
4 {
5
6 int r;
7 r=a+b;
8
9 return r; The result is 8
10
11 }
12
13
14 int main ()
15
16 {
17
int z;
z = addition (5,3);
cout << "The result is " << z;

Chapter Seven: Function [Type here] Page 2 of 30


return 0;
}

This program is divided in two functions: addition and main. Remember that no
matter the order in which they are defined, a C++ program always starts by calling main.
In fact, main is the only function called automatically, and the code in any other function
is only executed if its function is called from main (directly or indirectly).
In the example above, main begins by declaring the variable z of type int, and right
after that, it performs the first function call: it calls addition. The call to a function
follows a structure very similar to its declaration. In the example above, the call to
addition can be compared to its definition just a few lines earlier:

The parameters in the function declaration have a clear correspondence to the


arguments passed in the function call. The call passes two values, 5 and 3, to the
function; these correspond to the parameters a and b, declared for function addition.
At the point at which the function is called from within main, the control is passed to
function addition: here, execution of main is stopped, and will only resume once the
addition function ends. At the moment of the function call, the value of both arguments
(5 and 3) are copied to the local variables int a and int b within the function.
Then, inside addition, another local variable is declared (int r), and by means of the
expression r=a+b, the result of a plus b is assigned to r; which, for this case, where a is 5
and b is 3, means that 8 is assigned to r.
The final statement within the function:

return r;

Ends function addition, and returns the control back to the point where the function
was called; in this case: to function main. At this precise moment, the program resumes
its course on main returning exactly at the same point at which it was interrupted by the
call to addition. But additionally, because addition has a return type, the call is evaluated

Chapter Seven: Function [Type here] Page 3 of 30


as having a value, and this value is the value specified in the return statement that ended
addition: in this particular case, the value of the local variable r, which at the moment of
the return statement had a value of 8.

Therefore, the call to addition is an expression with the value returned by the
function, and in this case, that value, 8, is assigned to z. It is as if the entire function call
(addition(5,3)) was replaced by the value it returns (i.e., 8).
Then main simply prints this value by calling:

cout << "The result is " << z;

A function can actually be called multiple times within a program, and its argument
is naturally not limited just to literals:

// function example
#include <iostream>

1 using namespace std;


2
int subtraction (int a, int b)
3
4 {
5
6 int r;
7
8 r=a-b;
The first result is 5
9 return r;
10 The second result is 5
11 }
12 The third result is 2
13 int main ()
The fourth result is 6
14 {
15
16 int x=5, y=3, z;
17
18 z = subtraction (7,2);
19
cout << "The first result is " << z << '\n';
20
21 cout << "The second result is " << subtraction (7,2) << '\n';

cout << "The third result is " << subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);

Chapter Seven: Function [Type here] Page 4 of 30


cout << "The fourth result is " << z << '\n';
return 0;
}

Similar to the addition function in the previous example, this example defines a
subtract function, that simply returns the difference between its two parameters. This
time, main calls this function several times, demonstrating more possible ways in which a
function can be called.
Let's examine each of these calls, bearing in mind that each function call is itself an
expression that is evaluated as the value it returns. Again, you can think of it as if the
function call was itself replaced by the returned value:

1 z = subtraction (7,2);
2 cout << "The first result is " << z;

If we replace the function call by the value it returns (i.e., 5), we would have:

1 z = 5;
2 cout << "The first result is " << z;

With the same procedure, we could interpret:

cout << "The second result is " << subtraction (7,2);

as:

cout << "The second result is " << 5;

since 5 is the value returned by subtraction (7,2).In the case of:

cout << "The third result is " << subtraction (x,y);

The arguments passed to subtraction are variables instead of literals. That is also
valid, and works fine. The function is called with the values x and y have at the moment
of the call: 5 and 3 respectively, returning 2 as result.
The fourth call is again similar:

Chapter Seven: Function [Type here] Page 5 of 30


z = 4 + subtraction (x,y);

The only addition being that now the function call is also an operand of an addition
operation. Again, the result is the same as if the function call was replaced by its result: 6.
Note, that thanks to the commutative property of additions, the above can also be written
as:

z = subtraction (x,y) + 4;

With exactly the same result. Note also that the semicolon does not necessarily go
after the function call, but, as always, at the end of the whole statement. Again, the logic
behind may be easily seen again by replacing the function calls by their returned value:

1 z = 4 + 2; // same as z = 4 + substraction (x,y);


2 z = 2 + 4; // same as z = substraction (x,y) + 4;

Function Declaration
In C++, identifiers can only be used in expressions once they have been declared.
Function declaration, is done to tell the compiler about the existence of the function.
Function's return type, its name & parameter list is mentioned. Function body is written
in its definition.
The general format for a prototype is simple:

return-type function_name ( parameter_type, ..., parameter_type );

paramter_type just means the type for each paramenter -- for instance, an int, a
float, or a char. It's exactly the same thing as what you would put if you were declaring a
variable.
Functions cannot be called before they are declared. That is why, in all the previous
examples of functions, the functions were always defined before the main function,
which is the function from where the other functions were called. If main were defined

Chapter Seven: Function [Type here] Page 6 of 30


before the other functions, this would break the rule that functions shall be declared
before being used, and thus would not compile.
The prototype of a function can be declared without actually defining the function
completely, giving just enough details to allow the types involved in a function call to be
known. Naturally, the function shall be defined somewhere else, like later in the code. At
least, once declared like this, it can already be called.
The declaration shall include all types involved (the return type and the type of its
arguments), using the same syntax as used in the definition of the function, but replacing
the body of the function (the block of statements) with an ending semicolon.
The parameter list does not need to include the parameter names, but only their
types. Parameter names can nevertheless be specified, but they are optional, and do not
need to necessarily match those in the function definition.
Lets understand this with help of an example.

#include < iostream>


using namespace std;
int sum (int , int ); //declaring function
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}
int sum (int x, int y) //defining function
{
return (X + y);
}

Here, initially the function is declared, without body. Then inside main() function it
is called, as the function returns sumation of two values, hence z is their to store the
value of sum. Then, at last, function is defined, where the body of function is mentioned.
We can also, declare & define the function together, but then it should be done before it
is called.
For example, a function called protofunction with two int parameters can be declared
with either of these statements:
int protofunction (int first, int second);

Chapter Seven: Function [Type here] Page 7 of 30


int protofunction (int, int);

Anyway, including a name for each parameter always improves legibility of the
declaration.

// declaring functions prototypes


#include <iostream>
using namespace std;
void odd (int x);
void even (int x);

1
2 int main()
3
4 {
5
int i;
6
7 do {
8
cout << "Please, enter number (0 to Please, enter number (0 to exit): 9
9
10 exit): "; It is odd.
11
12 cin >> i; Please, enter number (0 to exit): 6
13 odd (i);
14 It is even.
15 } while (i!=0); Please, enter number (0 to exit):
16 1030
17 return 0;
18 } It is even.
19
20 Please, enter number (0 to exit): 0
21
It is even.
22 void odd (int x)
23
{
24
25 if ((x%2)!=0) cout << "It is odd.\n";
26
27 else even (x);
28
29 }
void even (int x)
{
if ((x%2)==0) cout << "It is
even.\n";
else odd (x);
}

Chapter Seven: Function [Type here] Page 8 of 30


This example is indeed not an example of efficiency. You can probably write yourself
a version of this program with half the lines of code. Anyway, this example illustrates
how functions can be declared before its definition:
The following lines:

1 void odd (int a);


2 void even (int a);

Declare the prototype of the functions. They already contain all what is necessary to
call them, their name, the types of their argument, and their return type (void in this case).
With these prototype declarations in place, they can be called before they are entirely
defined, allowing for example, to place the function from where they are called (main)
before the actual definition of these functions.
However, declaring functions before being defined is not only useful to reorganize
the order of functions within the code. In some cases, such as in this particular case, at
least one of the declarations is required, because odd and even are mutually called; there
is a call to even in odd and a call to odd in even. In addition, therefore, there is no way to
structure the code so that odd is defined before even, and even before odd.

Calling a Function

One of the main reasons of using various functions in your program is to isolate
assignments; this allows you to divide the jobs among different entities so that if
something is going wrong, you might easily know where the problem is. Functions trust
each other, so much that one function does not have to know HOW the other function
performs its assignment. One function simply needs to know what the other function
does, and what that other function needs.
When calling one function from another function, provide neither the return value
nor the body, simply type the name of the function and its list of arguments, if any. For
example, to call a function named Welcome() from the main() function, simply type it,
like this:

Chapter Seven: Function [Type here] Page 9 of 30


#include <iostream>

using namespace std;

void Message()

cout << "This is C++ in its truest form.";

int main()

Message(); // Calling the Message() function

return 0;

void Functions

A function that does not return a value is declared and defined as void. Here is an
example:

void Introduction()
{
cout << "This program is used to calculate the areas of some
shapes.\n"
<< "The first shape will be a square and the second, a
rectangle.\n"
<< "You will be requested to provide the dimensions and the
program "
<< "will calculate the areas";
}

Any function could be a void type as long as you are not expecting it to return a
specific value. A void function with a more specific assignment could be used to
calculate and display the area of a square. Here is an example:

void SquareArea()
{
double Side;

Chapter Seven: Function [Type here] Page 10 of 30


cout << "\nEnter the side of the square: ";
cin >> Side;

cout << "\nSquare characteristics:";


cout << "\nSide = " << Side;
cout << "\nArea = " << Side * Side;
}

When a function is of type void, it cannot be displayed on the same line with the cout
extractor and it cannot be assigned to a variable (since it does not return a value).
Therefore, a void function can only be called.

The Type of Return Value

The purpose of a function identifies what the function is meant to do. When a
function has carried its assignment, it provides a result. For example, if a function is
supposed to calculate the area of a square, the result would be the area of a square. The
result of a function used to get a studen first name would be a word representing a student
first name. The result of a function is called a return value. A function is also said to
return a value.
There are two forms of expectations you will have from a function: a specific value or
a simple assignment. If you want the function to perform an assignment without giving
you back a result, such a function is qualified as void and would be declared as

void FunctionName();

A return value, if not void, can be any of the data types we have studied so far. This
means that a function can return a char, an int, a float, a double, a bool, or a string.

double FunctionName();
char FunctionName();
bool FunctionName();
string FunctionName();

If you declare a function that is returning anything (a function that is not void), the
compiler will need to know what value the function returns. The return value must be the
same type declared. The value is set with the return keyword.

Chapter Seven: Function [Type here] Page 11 of 30


If a function is declared as a char, make sure it returns a character (only one
character). Here is an example:

char Answer()
{
char a;
cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? ";
cin >> a;
return a;
}

The return value can also be an expression. Here is an example:

double SquareArea(double Side)


{
return (Side * Side);
}

A return value could also be a variable that represents the result. Here is example:

double SquareArea(double Side)


{
double Area;
Area = Side * Side;
return Area;
}

If a function returns a value (other than void), a calling function can assign its result
to a local variable. Here is an example:
#include <iostream>

using namespace std;

int GetMajor()

int Choice;

cout << "\n1 - Business Administration";

cout << "\n2 - History";

Chapter Seven: Function [Type here] Page 12 of 30


cout << "\n3 - Geography";

cout << "\n4 - Education";

cout << "\n5 - Computer Sciences";

cout << "\nYour Choice: ";

cin >> Choice;

return Choice;

int main()

int Major;

cout << "Welcome to the student orientation program.";

cout << "Select your desired major:";

Major = GetMajor();

cout << "You select " << Major;

cout << "\n";

return 0;

You can also directly display the result of a function using the cout operator. In
this case, after typing cout and its << operator, type the function name and its arguments
names, if any.

Functions with no type. The use of void

The syntax for functions:

type name ( argument1, argument2 ...) { statements }

Chapter Seven: Function [Type here] Page 13 of 30


Requires the declaration to begin with a type. This is the type of the value returned by
the function. But what if the function does not need to return a value? In this case, the
type to be used is void, which is a special type to represent the absence of value. For
example, a function that simply prints a message may not need to return any value:

// void function example


#include <iostream>
1 using namespace std;
2
3 void printmessage ()
4 {
5
6 cout << "I'm a function!";
7 I'm a function!
8 }
9
int main ()
10
11 {
12
13 printmessage ();
return 0;
}

void can also be used in the function's parameter list to explicitly specify that the
function takes no actual parameters when called. For example, printmessage could have
been declared as:

void printmessage (void)


1
2{
3 cout << "I'm a function!";
4
}

In C++, an empty parameter list can be used instead of void with same meaning, but
the use of void in the argument list was popularized by the C language, where this is a
requirement.
Something that in no case is optional are the parentheses that follow the function
name, neither in its declaration nor when calling it. And even when the function takes no

Chapter Seven: Function [Type here] Page 14 of 30


parameters, at least an empty pair of parentheses shall always be appended to the function
name. See how printmessage was called in an earlier example:

printmessage ();

The parentheses are what differentiate functions from other kinds of declarations or
statements. The following would not call the function:

printmessage;

Default Arguments

Whenever a function takes an argument, that argument is required. If the calling


function does not provide the (required) argument, the compiler would throw an error.
In C++, functions can also have optional parameters, for which no arguments are
required in the call, in such a way that, for example, a function with three parameters may
be called with only two. For this, the function shall include a default value for its last
parameter, which is used by the function when called with fewer arguments.
Imagine you write a function that will be used to calculate the final price of an item
after discount. The function would need the discount rate in order to perform the
calculation. Such a function could look like this:
double CalculateNetPrice(double OrigPrice ,double discountRate)

return origPrice - (origPrice * discountRate / 100);

Since this function expects 2 argument, if you do not supply it, the following program
would not compile:
#include <iostream>

using namespace std;

Chapter Seven: Function [Type here] Page 15 of 30


double CalculateNetPrice(double OrigPrice ,double discountRate)

return origPrice - (origPrice * discountRate / 100);

int main()

double finalPrice;

double discount = 15; // That is 25% = 25

double OrigPrice = 100;

finalPrice = CalculateNetPrice(OrigPrice);

cout << "\nFinal Price = " << finalPrice << "\n\n";

return 0;

Most of the time, a function such as ours would use the same discount rate over and
over again. Therefore, instead of supplying an argument all the time, C++ allows you to
define an argument whose value would be used whenever the function is not provided
with the argument.
To give a default value to an argument, when declaring the function, type the name of
the argument followed by the assignment operator, followed by the default value. The
CalculateNetPrice() function, with a default value, could be defined as:
#include <iostream>

using namespace std;

double CalculateNetPrice(double OrigPrice ,double discountRate = 25)

double origPrice;

cout << "Please enter the original price: ";

Chapter Seven: Function [Type here] Page 16 of 30


cin >> origPrice;

return origPrice - (origPrice * discountRate / 100);

int main()

double finalPrice;

double OrigPrice = 100;

finalPrice = calculateNetPrice(OrigPrice);

cout << "\nFinal Price = " << finalPrice << "\n\n";

return 0;

If a function takes more than one argument, you can provide a default argument for
each and select which ones would have default values. If you want all arguments to have
default values, when defining the function, type each name followed by = followed by the
desired value. Here is an example:
#include <iostream>

using namespace std;

double CalculateNetPrice(double OrigPrice, double tax = 5.75, double discount = 25)

double discountValue = origPrice * discount / 100;

double taxValue = tax / 100;

double netPrice = origPrice - discountValue + taxValue;

cout << "Original Price: $" << origPrice << endl;

cout << "Discount Rate: " << discount << "%" << endl;

Chapter Seven: Function [Type here] Page 17 of 30


cout << "Tax Amount: $" << tax << endl;

return netPrice;

int main()

double finalPrice;

double origPrice = 245.55

finalPrice = CalculateNetPrice(origPrice);

cout << "Final Price: $" << finalPrice << "\n\n";

return 0;

}
Here is the result produced:

Original Price: $245.55

Discount Rate: 25%

Tax Amount: $5.75

Final Price: $184.22

Press any key to continue...

If the function receives more than two arguments and you would like only some
of those arguments to have default values, the arguments that would have default

Chapter Seven: Function [Type here] Page 18 of 30


values must be at the end (right side) of the list. Regardless of how many arguments
would or would not have default values, start the list of arguments without those
that would not use default values.

Calling a Function by Value

In this calling technique, we pass the values of arguments, which are stored or copied,
into the formal parameters of functions. Hence, the original values are unchanged only
the parameters inside function change

void calc(int x);


void main()
{
int x = 10;
calc(x);
cout<<x;
}
void calc(int x)
{
x = x + 10 ;
}
Output : 10

In this case the actual variable x is not changed, because we pass argument by value,
hence a copy of x is passed, which is changed, and that copied value is destroyed as the
function ends(goes out of scope). So the variable x inside main() still has a value 10.
But we can change this program to modify the original x, by making the function
calc() return a value, and storing that value in x.

int calc(int x);


void main()
{
int x = 10;
x = calc(x);
cout<< x;
}
int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20

Chapter Seven: Function [Type here] Page 19 of 30


Calling a Function by Reference

In this we pass the address of the variable as arguments. In this case the formal
parameter can be taken as a reference or a pointer, in both the case they will change the
values of the original variable.

void calc(int& x);


void main()
{
int x = 10;
calc(x);
cout<<x;
}
void calc(int& x)
{
x = x + 10 ;
}
Output : 20

For example, take:

1 int x=5, y=3, z;


2 z = addition ( x, y );

In this case, function addition is passed 5 and 3, which are copies of the values of x
and y, respectively. These values (5 and 3) are used to initialize the variables set as
parameters in the function's definition, but any modification of these variables within the
function has no effect on the values of the variables x and y outside it, because x and y
were themselves not passed to the function on the call, but only copies of their values at
that moment.

In certain cases, though, it may be useful to access an external variable from within a
function. To do that, arguments can be passed by reference, instead of by value. For
example, the function duplicate in this code duplicates the value of its three arguments,
causing the variables used as arguments to actually be modified by the call:

Chapter Seven: Function [Type here] Page 20 of 30


// passing parameters by reference
#include <iostream>
using namespace std;

1
2 void duplicate (int& a, int& b, int& c)
3
{
4
5 a*=2;
6
7 b*=2;
8
9 c*=2;
x=2, y=6, z=14
10 }
11
12
13
14 int main ()
15
{
16
17 int x=1, y=3, z=7;
18
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}

To gain access to its arguments, the function declares its parameters as references. In
C++, references are indicated with an ampersand (&) following the parameter type, as in
the parameters taken by duplicate in the example above.
When a variable is passed by reference, what is passed is no longer a copy, but the
variable itself, the variable identified by the function parameter, becomes somehow
associated with the argument passed to the function, and any modification on their
corresponding local variables within the function are reflected in the variables passed as
arguments in the call.

In fact, a, b, and c become aliases of the arguments passed on the function call (x, y,
and z) and any change on a within the function is actually modifying variable x outside

Chapter Seven: Function [Type here] Page 21 of 30


the function. Any change on b modifies y, and any change on c modifies z. That is why
when, in the example, function duplicate modifies the values of variables a, b, and c,
the values of x, y, and z are affected.
If instead of defining duplicate as:

void duplicate (int& a, int& b, int& c)

Was it to be defined without the ampersand signs as:

void duplicate (int a, int b, int c)

The variables would not be passed by reference, but by value, creating instead copies
of their values. In this case, the output of the program would have been the values of x, y,
and z without being modified (i.e., 1, 3, and 7).

Function Overloading

A C++ program involves a great deal of names that represent variables and functions
of various kinds. The compiler does not allow two variables to have the same name in the
same function. Although two functions should have unique names in the same
program, C++ allows you to use the same name for different functions of the same
program following certain rules. The ability to have various functions with the same
name in the same program is called function overloading. The most important rule about
function overloading is to make sure that each one of these functions has a
1. different number
2. or different type(s) of arguments.
For example:

1
2 // overloading functions
3 #include <iostream> 10
4
5 using namespace std; 2.5
6
7
8

Chapter Seven: Function [Type here] Page 22 of 30


9 int operate (int a, int b)
10
11 {
12 return (a*b);
13
14 }
15
16
17
double operate (double a, double b)
18
19 {
20
21 return (a/b);
22
}

int main ()
{
int x=5,y=2;
double n=5.0,m=2.0;
cout << operate (x,y) << '\n';
cout << operate (n,m) << '\n';
return 0;
}

In this example, there are two functions called operate, but one of them has two
parameters of type int, while the other has them of type double. The compiler knows
which one to call in each case by examining the types passed as arguments when the
function is called. If it is called with two int arguments, it calls to the function that has
two int parameters, and if it is called with two doubles, it calls the one with two
doubles.

In this example, both functions have quite different behaviors, the int version
multiplies its arguments, while the double version divides them. This is generally not a
good idea. Two functions with the same name are generally expected to have -at least- a
similar behavior, but this example demonstrates that is entirely possible for them not to.
Two overloaded functions (i.e., two functions with the same name) have entirely different
definitions; they are, for all purposes, different functions, that only happen to have the
same name.

Chapter Seven: Function [Type here] Page 23 of 30


Note that a function cannot be overloaded only by its return type. At least one of its
parameters must have a different type.
Overloaded functions may have the same definition. For example:

// overloaded functions
#include <iostream>
using namespace std;

1 int sum (int a, int b)


2
3 {
4
return a+b;
5
6 }
7
8
9
10 double sum (double a, double b) 30
11 { 2.5
12
13 return a+b;
14
15 }
16
17
18 int main ()
19
20 {
cout << sum (10,20) << '\n';
cout << sum (1.0,1.5) << '\n'
return 0;
}

Here, sum is overloaded with different parameter types, but with the exact same body.

Inline Functions

Calling a function generally causes a certain overhead (stacking arguments, jumps,


etc...), and thus for very short functions, it may be more efficient to simply insert the code
of the function where it is called, instead of performing the process of formally calling a
function.

Chapter Seven: Function [Type here] Page 24 of 30


Preceding a function declaration with the inline specifier informs the compiler that
inline expansion is preferred over the usual function call mechanism for a specific
function. This does not change at all the behavior of a function, but is merely used to
suggest the compiler that the code generated by the function body shall be inserted at
each point the function is called, instead of being invoked with a regular function call.

For example, the concatenate function above may be declared inline as:
inline string concatenate (const string& a, const string& b)

return a+b;

This informs the compiler that when concatenate is called, the program prefers the
function to be expanded inline, instead of performing a regular call. inline is only
specified in the function declaration, not when it is called.
Note that most compilers already optimize code to generate inline functions when
they see an opportunity to improve efficiency, even if not explicitly marked with the
inline specifier. Therefore, this specifier merely indicates the compiler that inline is
preferred for this function, although the compiler is free to not inline it, and optimize
otherwise. In C++, optimization is a task delegated to the compiler, which is free to
generate any code for as long as the resulting behavior is the one specified by the code.
#include <iostream>

using namespace std;

inline void Area(float Side)

cout << "The area of the square is " << Side * Side;

Chapter Seven: Function [Type here] Page 25 of 30


}

int main()

float s;

cout << "Enter the side of the square: ";

cin >> s;

Area(s);

return 0;

You can also use the keyword on an inline function. To declare a function as inline
and, type both words at the beginning of the declaration. The following program requests
the hourly salary from the user. Then it calculates the periodic earnings:

#include <iostream>
using namespace std;

void inline RequestSalary(double& h);


inline double Daily(double h);
double inline Weekly(double h);
inline double BiWeekly(double h);
double inline Monthly(double h);
double inline Yearly(double h);

int main()
{
double HourlySalary;

cout << "This program allows you to evaluate your salary "
<< "for different periods\n";

RequestSalary(HourlySalary);

cout << "\nBased on the hourly rate you supplied, here are your "
<< "periodic earnings";
cout << "\n\tHourly: $" << HourlySalary;
cout << "\n\tDaily: $" << Daily(HourlySalary);
cout << "\n\tWeekly: $" << Weekly(HourlySalary);
cout << "\n\tBi-Weekly: $" << BiWeekly(HourlySalary);
cout << "\n\tMonthly: $" << Monthly(HourlySalary);
cout << "\n\tYearly: $" << Yearly(HourlySalary);

cout << "\n\n";


return 0;

Chapter Seven: Function [Type here] Page 26 of 30


}
void inline RequestSalary(double& x)
{
cout << "Enter your hourly salary: $";
cin >> x;
}
inline double Daily(double x)
{
return x * 8;
}
double inline Weekly(double x)
{
return Daily(x) * 5;
}
inline double BiWeekly(double x)
{
return Weekly(x) * 2;
}
double inline Monthly(double x)
{
return Weekly(x) * 4;
}
double inline Yearly(double h)
{
return Monthly(h) * 12;
}

Variable storage types

Scopes Name Visibilty


Named entities, such as variables, functions, and compound types need to be declared
before being used in C++. The point in the program where this declaration happens
influences its visibility:
An entity declared outside any block has global scope, meaning that its name is valid
anywhere in the code. While an entity declared within a block, such as a function or a
selective statement, has block scope, and is only visible within the specific block in which
it is declared, but not outside it. Variables with block scope are known as local variables.

Chapter Seven: Function [Type here] Page 27 of 30


Function variables are stored in three different places.
1. Local Variable: Variables declared within a function are said to be local

In the following example, the variable localVariable is local to the function fn():
int globalVariable;
void fn()
{
int localVariable;
static int staticVariable;
}

The variable localVariable doesn't exist until the function fn() is called.
localVariable ceases to exist when the function returns. Upon return, whatever
value that is stored in localVariable is lost. In addition, only fn() has access to
localVariable other functions cannot reach into the function to access it.
2. Global Variable exists as long as the program is running. All functions have
access to global Variable all of the time.
Example:
For example, a variable declared in the body of a function is a local variable that
extends until the end of the the function (i.e., until the brace } that closes the function
definition), but not outside it:
int foo; // global variable
int some_function ()
{
int bar; // local variable
bar = 0;
}
int other_function ()
{
foo = 1; // ok: foo is a global variable
bar = 2; // wrong: bar is not visible from this function
}

In each scope, a name can only represent one entity. For example, there cannot be two
variables with the same name in the same scope:
int some_function ()
{
int x;
x = 0;
double x; // wrong: name already used in this scope
x = 0.0;

Chapter Seven: Function [Type here] Page 28 of 30


}

3. Static Variable is something of a mix between a local and a global variable.


The variable static Variable is created when execution first reaches the declaration. In
addition, static Variable is only accessible within function. Unlike local Variable,
however, static Variable continues to exist even after the program returns from function.
If function assigns a value to static Variable once, it will still be there the next time that
function is called.

Because static member variables are not part of the individual objects, you must
explicitly define the static member if you want to initialize it to a non-zero value. In the
absence of an initializing line, C++ will initialize the value to 0.

Example:
int GenerateID()
{
static int s_nID = 0;
return s_nID++;
}
int main()
{
std::cout << GenerateID() << std::endl;
std::cout << GenerateID() << std::endl;
std::cout << GenerateID() << std::endl;
return 0;
}
This program prints:

0
1
2

Note that s_nID has kept its value across multiple function calls.
These static variables are stored on static storage area , not in stack.
void counter()
{
static int count=0;
cout << count++;
}

int main(0
{
for(int i=0;i<5;i++)
{

Chapter Seven: Function [Type here] Page 29 of 30


counter();
}
}
Output : 0 1 2 3 4
Let's se the same program's output without using static variable.
void counter()
{
int count=0;
cout << count++;
}

int main(0
{
for(int i=0;i<5;i++)
{
counter();
}
}
Output : 0 0 0 0 0

Chapter Seven: Function [Type here] Page 30 of 30

Anda mungkin juga menyukai