Introduction to Built-In Functions
Introduction to Built-In Functions
C++ Built-in Functions
Introduction
Although as a smart programmer you can create any function to perform a desired job, the C++ language provides a series of functions already made so you can just add them to your program without caring how they work, all you need to know is what these functions do. The functions that are part of the C++ language are highly valuable, were tested sufficiently, and are completely reliable. The C++ built-in functions are made for various assignments ranging from algebra, geometry, trigonometry, and finance, etc. Besides the functions that are part of the C++ Standard, each compiler ships with its own set of functions that may not be available on other compilers. Borland C++ Builder provides an extremely rich library of functions.
Asserting a Value or an Expression
Most of the values you use in your program will need to fit in an interval of your choice. For example, when requesting the age of a person, you would need such a value to be positive. After all, you do not expect a person to be 26 years old. C++ provides a function that can be used to check that a value or expression responds to a criteria of your choice. This function is called assert() and is defined in the cassert library of the std namespace. Its syntax is:
void assert(int Expression);
The assert() function considers an expression as its argument and tests it. This function is used in the same context as the conditional statements we will study in the next lesson of this book. If the Expression is true, assert() acknowledges that and lets the compiler continue with the next operation. If the Expression is false, assert() displays a (nasty) message. Although we have not yet learned conditional statements, the following is an example that requests the age of a student and checks that the supplied age is valid only if the student is older than 8:
#include <iostream>
#include <cassert>
using namespace std;
int main()
{
float StudentAge;
cout << "Type Student's Age: ";
cin >> StudentAge;
assert(StudentAge > 8);
cout << "Student Age: " << StudentAge << "\n\n";
}
Mathematic Functions
The C++ language also provides a series of functions to perform various mathematically related operations. The functions are defined in various libraries and this can depend on the compiler you are using. The functions defined in the cmath library are:
| acos | cos | fmod | modf | tan |
| asin | cosh | frexp | pow | tanh |
| atan | exp | ldexp | sin | |
| atan2 | fabs | log | sinh | |
| ceil | floor | log10 | sqrt |
Additional functions are defined in the cstdlib library and they are:
| abs | labs | srand |
| div | ldiv | rand |
Functions and Namespaces
Functions Local Definition
Like a variable, a function can be part of a namespace. To declare a function in a namespace, provide its return type, followed by a name, followed by the argument(s), if any, inside of parentheses. Here is an example:
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double CalculateDiscount();
double CalculateInterest();
double CalculateMaturity();
}
A member function of a namespace can be accessed using the scope access operator.
There are two main ways you can implement a member function. In the body of the namespace, which is a local implementation, delimit the body of the function with an opening curly bracket { and a closing curly bracket }. A function that is a member of a namespace has complete access to the member variables of the same namespace. Therefore, you do not have to pass the member variables as arguments to the member functions. Here is an example:
#include <iostream>
using namespace std;
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double GetInterestRate()
{
return Rate / 100;
}
double CalculateInterest()
{
return Principal * GetInterestRate() * Time;
}
double CalculateMaturity()
{
return Principal + CalculateInterest();
}
}
int main()
{
using namespace InterestAndDiscount;
Principal = 12500; // $
Rate = 12.25; // %
Time = 4; // Years
cout << "Interest Calculation";
cout << "\nPrincipal: $" << Principal
<< "\nRate: " << Rate << "%"
<< "\nTime: " << Time << " years"
<< "\nInterest: $" << CalculateInterest()
<< "\nMaturity: $" << CalculateMaturity() << "\n\n";
}
This would produce:
Interest Calculation
Principal: $12500
Rate: 12.25%
Time: 4 years
Interest: $6125
Maturity: $18625
If a nested namespace has its own functions, you can also implement them in the body of the nested namespace. Here is an example:
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double GetInterestRate()
{
return Rate / 100;
}
double CalculateInterest()
{
return Principal * GetInterestRate() * Time;
}
double CalculateMaturity()
{
return Principal + CalculateInterest();
}
namespace Discounter
{
double Maturity;
double DiscountRate;
double TermOfDiscount;
double Discount()
{
return Maturity * DiscountRate * TermOfDiscount;
}
}
}
After locally implementing the member functions of a nested namespace, you can access its members and display their value in the main() function as done above.
Functions Global Definitions
To implement a member function outside the body of a namespace, provide the return type, followed by the name of the namespace, followed by the scope access operator ::. Here is an example:
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double GetInterestRate();
double CalculateInterest();
double CalculateMaturity();
}
InterestAndDiscount::GetInterestRate()
{
return Rate / 100;
}
InterestAndDiscount::CalculateInterest()
{
return Principal * GetInterestRate() * Time;
}
InterestAndDiscount::CalculateMaturity()
{
return Principal + CalculateInterest();
}
To implement the member functions of a nested namespace outside of the parent namespace, you must qualify each member function to specify the function (or the variable) you are calling. Here is an example:
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double GetInterestRate();
double CalculateInterest();
double CalculateMaturity()
namespace Discounter
{
double Maturity;
double DiscountRate;
double TermOfDiscount;
double Discount();
}
}
. . .
InterestAndDiscount::Discounter::Discount()
{
return Maturity * DiscountRate * TermOfDiscount;
}
Namespaces and External Functions
The member variables of a namespace are variables like any of those we have used so far. They can request their values from an outside function. Here is an example:
#include <iostream>
using namespace std;
namespace InterestAndDiscount
{
. . .
}
. . .
int main()
{
using namespace InterestAndDiscount;
double GetThePrincipal();
cout << "Loan Processing\n";
cout << "Enter the following values\n";
Principal = GetThePrincipal();
cout << "Rate (between 0 and 100): ";
cin >> Rate;
cout << "Time (number of years): ";
cin >> Time;
cout << "\nInterest on a loan";
cout << "\nPrincipal: $" << Principal;
cout << "\nRate: " << Rate << "%";
cout << "\nTime: " << Time << " years";
cout << "\nInterest: $" << CalcInterest();
cout << "\nMaturity Value: $" << CalcMaturityValue();
}
double GetThePrincipal()
{
double P;
cout << "Principal: $";
cin >> P;
return P;
}
The member variable of a namespace can also be passed as argument to a function. When passing the argument, if the using namespace routine has been entered, you can pass the argument like any other. Otherwise, you should qualify the namespace member with the :: operator. In the following example, one member of a namespace is passed by its name only because of the previous using namespace. The other members are passed by being qualified, which is for demonstration purposes only:
#include <iostream>
using namespace std;
namespace InterestAndDiscount
{
. . .
}
. . .
int main()
{
using namespace InterestAndDiscount;
void GetThePrincipal(double& p);
void RateAndTime(double &r, double &t);
cout << "Loan Processing";
cout << "\nEnter the following values\n";
GetThePrincipal(Principal);
RateAndTime(InterestAndDiscount::Rate, InterestAndDiscount::Time);
cout << setiosflags(ios::fixed) << setprecision(2);
cout << "\nInterest on a loan";
cout << "\nPrincipal: $" << Principal;
cout << "\nRate: " << Rate << "%";
cout << setiosflags(ios::fixed) << setprecision(0);
cout << "\nTime: " << Time << " years";
cout << setiosflags(ios::fixed) << setprecision(2);
cout << "\nInterest: $" << CalcInterest();
cout << "\nMaturity Value: $" << CalcMaturityValue();
}
void GetThePrincipal(double& P)
{
cout << "Principal: $";
cin >> P;
while( P < 0 )
{
cout << "Enter a positive number: $";
cin >> P;
}
}
void RateAndTime(double &rate, double &time)
{
do {
cout << "Rate (between 0 and 100): ";
cin >> rate;
} while(rate < 0 || rate > 100);
do {
cout << "Time (Nbr of Years): ";
cin >> time;
} while(time <= 0 || time >= 30);
}
C++ and Files
Introduction
A computer application is primarily a series of files put together to compose a single entity. With previous generations of programming, you had to create text files, save them with a .c, a .cc, or a .cpp extension, link them and compile them. Many modern programming environments allow you to create the files and hand them to the compiler that would link them as a project, and then create an executable. In reality, the process has not changed, it has only been made easier and faster. Still, because the programming environments are developed by different companies, each presents its own way of creating the necessar files, compiling them, and creating an executable.
When writing a program, the main reason for using functions is to isolate assignments. This allows you to effectively troubleshoot problems when they arise (because they will arise, not if but when). For example, if you are asked to write a program that would process orders at a department store, you can write one long main() function that would process all requests and orders. When the store is having a sale and you need to apply a discount to the program, you would spend time looking for the sections that use the discount and calculate the price. If you use functions to isolate assignments, you can easily find out which particular function deals with discount; all you would have to do is change the discount value without having to read the whole program.
Practical Learning: Creating a File
Header Files
When using functions in a program, we found out that the order of declaring functions was important. For example, you cannot call a function that has not been declared yet. For this reason, whenever you need to call a function, you should find out where it was created or whether it has been declared already. If the program is using many functions, it would become cumbersome to start looking for functions. At the same time, on a large program, it is usual for many functions to use the same kind of variable. Although you can locally declare the same variable needed by a function, if these functions of the same program would need to exchange values among them, you should declare some variables globally, usually on top of the file, then make such a variable available to any function that needs it.
To make these functions and variables easily manageable, you can create one file where you would list the functions and variables used in a program. Such a file is called a header file and it has the h extension.
File Preprocessors
As you are creating header files, if you work with a large team, you should avoid including in your program a file that has already been included. C++ allows you to avoid this by asking the compiler to check whether a header or a section of code has already been included in your program. This checking is performed using objects called preprocessors.
When using preprocessors to check whether a section of code or a file has already been included in your program, you start the file or the section with
#ifndef WhatToCheck
The preprocessors must start with the # symbol as we have been using on the #include preprocessor so far. The ifndef preprocessor, word for word, means If Not Defined. It refers to the word on its right side to check if that word has already been included. Because the #ifndef is used to check If WhatToCheck has not been defined yet, it can also be written as
#if !define WhatToCheck
Both would mean the same. In reality, what you would be asking this preprocessor to do is to check if the WhatToCheck word has not already been included. If it has not, then you would ask the compiler to define this section of code with the WhatToCheck word. To do this, you would decide that the section of code you want to delimit will be referred to with the WhatToCheck word. Therefore, the #ifndef preprocessor is followed by a
#define WhatToCheck
This means that if WhatToCheck has not been included yet, then it would be defined starting with the #define.
The section must end with the #endif preprocessor. This time, you do not need to specify what needs to be ended; the compiler will figure that out.
References
Referenced Variables
A reference is a variable name that is a duplicate of an existing variable. It provides a technique of creating more than one name to designate the same variable. To declare a reference variable, you use the reference operator expressed with the ampersand. The syntax of creating or declaring a reference is:
DataType &RefernceName = VariableName;
To declare a reference, type the variable’s name preceded by the same type as the variable it is referring to. Between the data type and the reference name, type the ampersand operator “&”. To specify what variable the reference is addressed to, use the assignment operator “=” followed by the name of the variable. The referred to variable must exist already. You cannot declare a reference as:
int &mine;
The compiler must know what variable you are referring to. Here is an example:
#include <iostream>
using namespace std;
int main()
{
int number = 228;
int &nbr = number;
}
The ampersand operator between the data type and the variable name can assume one of three positions as follows:
int& nbr; int & nbr; int &nbr;
As long as the & symbol is between a valid data type and a variable name, the compiler knows that the variable name (in this case Nbr) is a reference.
Once a reference has been initialized, it holds the same value as the variable it is referring to. You can then display the value of the variable using either of both:
#include <iostream>
using namespace std;
int main()
{
int number = 228;
int & nbr = number;
cout << "Number = " << number << "\n";
cout << "Its reference = " << nbr << "\n\n";
return 0;
}
If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:
#include <iostream>
using namespace std;
int main()
{
int number = 228; // Regular variable
int& nbr = number; // Reference
cout << "Number = " << number << "\n";
cout << "Its reference = " << nbr << "\n";
// Changing the value of the original variable
number = 4250;
cout << "\nNumber = " << number;
cout << "\nIts reference = " << nbr << "\n";
// Modifying the value of the reference
Nbr = 38570;
cout << "\nNumber = " << number;
cout << "\nIts reference = " << nbr << "\n\n";
}
In the same way, you can use either a reference or the variable it is referring to, to request the variable’s value from the user. Here is an example:
#include <iostream>
using namespace std;
int main()
{
double price;
double& refPrice = price;
cout << "What's the price? $";
cin >> price;
cout << "Price = $" << price << "\n";
cout << "Same as: $" << refPrice << "\n\n";
cout << "What's the price? $";
cin >> refPrice;
cout << "Price = $" << price << "\n";
cout << "Same as: $" << refPrice << "\n";
return 0;
}
If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:
#include <iostream>
using namespace std;
main()
{
int Number = 228; // Regular variable
int& Nbr = Number; // Reference
cout << "Number = " << Number << "\n";
cout << "Its reference = " << Nbr << "\n";
// Changing the value of the original variable
Number = 4250;
cout << "\nNumber = " << Number;
cout << "\nIts reference = " << Nbr << "\n";
// Modifying the value of the reference
Nbr = 38570;
cout << "\nNumber = " << Number;
cout << "\nIts reference = " << Nbr << "\n\n";
}
In the way, you can use either a reference or the variable it is referring to, to request the variable’s value from the user. Here is an example:
#include <iostream>
using namespace std;
main()
{
double Price;
double& RefPrice = Price;
cout << "What's the price? $";
cin >> Price;
cout << "Price = $" << Price << "\n";
cout << "Same as: $" << RefPrice << "\n\n";
cout << "What's the price? $";
cin >> RefPrice;
cout << "Price = $" << Price << "\n";
cout << "Same as: $" << RefPrice << "\n";
}
Referenced Functions
A function can be made to return a reference to a value. When defining such a function, make sure you type the reference operator to its left. After processing the function in its body, you must make sure you return a value that is a reference of the same type of the function. Here is an example:
#ifdef __BORLANDC__
#pragma argsused
#endif
#include <iostream>
using namespace std;
int &GetNumberOfPages()
{
int pp = 842;
int &pages = pp;
return pages;
}
int main( int argc, char * argv[] )
{
cout << "This book contains " << GetNumberOfPages() << " pages";
return 0;
}
If the function is not modifying any value it may have received, you can declare it as a constant:
#ifdef __BORLANDC__
#pragma argsused
#endif
#include <iostream>
using namespace std;
const int &GetNumberOfPages()
{
int pp = 842;
int &pages = pp;
return pages;
}
int main( int argc, char * argv[] )
{
cout << "This book contains " << GetNumberOfPages() << " pages";
return 0;
}
Static Variables and Functions
Static Variables
Consider the following program:
#include <iostream>
using namespace std;
void Starter(int y)
{
double a = 112.50;
double b = 175.25;
a = a / y;
b = b + 2;
cout << "y = " << y << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "b / a = " << b / a << "\n\n";
}
int main()
{
Starter(2);
Starter(2);
Starter(2);
Starter(2);
}
When executed, this program would produce:
y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 2 a = 56.25 b = 177.25 b / a = 3.15111
The Starter() function receives one argument passed when it is called. The called function also receives the same argument every time. Looking at the result, the argument passed to the function and the local variables declared inside of the called function keep the same value every time the function is called. That is, when the Starter() function is exited, the values remain the same.
We know that, when a function is defined, any variable declared locally belongs to the function and its influence cannot expand beyond the body of the function. If you want a locally declared variable to keep its changed value when its host function is exited, declare such a variable as static.
To declare a static variable, type the static keyword on the left of the variable’s data type. For example, if you plan to declare a Radius variable as static in an Area() function, you could write:
double Area()
{
static double Radius;
}
When you declare a variable as static, it is initialized with a 0 value. Otherwise, you can initialize it with a value of your choice when declaring it. To make the local variables of our Starter() function static, we can declare them as follows:
void Starter(int y)
{
static double a = 112.50;
static double b = 175.25;
a = a / y;
b = b + 2;
cout << "y = " << y << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "b / a = " << b / a << "\n\n";
}
|
This time, when executing the program, it would produce: |
y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 2 a = 28.125 b = 179.25 b / a = 6.37333 y = 2 a = 14.0625 b = 181.25 b / a = 12.8889 y = 2 a = 7.03125 b = 183.25 b / a = 26.0622
Notice that, this time, each local variable keeps its newly changed value when the function exits. Since a function’s argument can receive different values as the function is called different times, we can test our program by passing different values to its argument as follows:
#include <iostream>
using namespace std;
void Starter(int y)
{
static double a = 112.50;
static double b = 175.25;
a = a / y;
b = b + 2;
cout << "y = " << y << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "b / a = " << b / a << "\n\n";
}
int main()
{
Starter(2);
Starter(5);
Starter(14);
Starter(25);
return 0;
}
The current version of the program would produce:
y = 2 a = 56.25 b = 177.25 b / a = 3.15111 y = 5 a = 11.25 b = 179.25 b / a = 15.9333 y = 14 a = 0.803571 b = 181.25 b / a = 225.556 y = 25 a = 0.0321429 b = 183.25 b / a = 5701.11
Static Functions
Like a variable, a function also can be declared and/or defined as static. Here is an example:
#ifdef __BORLANDC__
#pragma argsused
#endif
#include <iostream>
// #include "Exercise.h"
using namespace std;
static int GetNumberOfPages()
{
int pages = 842;
return pages;
}
int main( int argc, char * argv[] )
{
cout << "This book contains " << GetNumberOfPages() << " pages";
return 0;
}
|
|
|||
| Previous | Copyright © 1998-2026, FunctionX | Saturday 12/28/2024, 19:20 | Next |
|
|
|||