Home

Exploring Functions

 

Introduction to Functions Parameters

 

Overview of Parameters

So far, we have learned how to declare and define simple functions. Imagine you want to write a program that calculates an item’s purchase price based on the item’s store price added the tax. The tax rate is a percentage value. This means a tax rate set at 7.50% in C++ terms is equal to 0.075 (because 7.50/100 = 0.075). The tax amount collected on a purchase is taken from an item’s price; its formula is:

The formula of calculating the final price of an item is:

Final Price = Item Price + Tax Amount

Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;

#pragma hdrstop

//---------------------------------------------------------------------------
#pragma argsused
double RequestOriginalPrice()
{
    double Price;

    cout << "Enter the original price: $";
    cin >> Price;
    return Price;
}
//---------------------------------------------------------------------------
double RequestDiscountRate()
{
    double Discount;

    cout << "Enter discount rate(0.00 to 100.00): ";
    cin >> Discount;
    return Discount;
}
//---------------------------------------------------------------------------
double RequestTaxRate()
{
    double Tax;

    cout << "Enter the tax rate(0.00 to 100.00): ";
    cin >> Tax;
    return Tax;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double OriginalPrice, DiscountRate, PriceAfterDiscount, TaxRate;
    double DiscountAmount, TaxAmount, NetPrice;

    OriginalPrice = RequestOriginalPrice();
    DiscountRate  = RequestDiscountRate();
    TaxRate       = RequestTaxRate();

    DiscountAmount = OriginalPrice * DiscountRate / 100;
    PriceAfterDiscount = OriginalPrice - DiscountAmount;
    TaxAmount = PriceAfterDiscount * TaxRate / 100;
    NetPrice = PriceAfterDiscount + TaxAmount;

    cout << "\n\nReceipt";
    cout << "\nOriginal Price:  $" << OriginalPrice;
    cout << "\nDiscount Amount: $" << DiscountAmount;
    cout << "\nAfter Discount:  $" << PriceAfterDiscount;
    cout << "\nTax Amount:      $" << TaxAmount;
    cout << "\nNet Price:       $" << NetPrice;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Enter the original price: $120
Enter discount rate(0.00 to 100.00): 20
Enter the tax rate(0.00 to 100.00): 5.75


Receipt
Original Price:  $120
Discount Amount: $24
After Discount:  $96
Tax Amount:      $5.52
Net Price:       $101.52
Press any key to continue...

We also learned to use files to group functions that share an assignment. Furthermore, to reduce the likelihood of name conflicts, we learned to create our entities in namespaces. An important aspect we need to study are the functions needs, that is, the external things a function would need in order to carry its assignment.

Practical Learning: Using Functions

  1. Create a new project using the Console Wizard. To save the project, on the Standard toolbar, click the Save All button.
  2. Create a new folder called GCS4 and display it in the Save In combo box. Save the unit as Main.cpp and save the project as CleaningOrders
  3. To create a new unit, on the Standard toolbar, click the New button and, in the New property page of the New Items dialog box, scroll down and double-click Unit.
  4. Save the unit as Orders
  5. Click the Orders.h tab and replace it as follows:
     
    //---------------------------------------------------------------------------
    #ifndef OrdersH
    #define OrdersH
    #include <iostream>
    #include <string>
    using namespace std;
    //---------------------------------------------------------------------------
    namespace GeorgetownCleaners
    {
    string GetCustomerName();
    int RequestNumberOfShirts();
    int RequestNumberOfPants();
    int RequestNumberOfOtherItems();
    double RequestAmountTended();
    }
    //---------------------------------------------------------------------------
    #endif
  6. Click the Orders.cpp tab and implement the functions as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Orders.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace GeorgetownCleaners
    {
    string GetCustomerName()
    {
        string FirstName, LastName, FullName;
    
        cout << "Enter customer identification\n";
        cout << "First Name: "; cin >> FirstName;
        cout << "Last Name:  "; cin >> LastName;
        FullName = FirstName + " " + LastName;
    
        return FullName;
    }
    //---------------------------------------------------------------------------
    int RequestNumberOfShirts()
    {
        int Shirts;
        cout << "Number of shirts: ";
        cin >> Shirts;
    
        return Shirts;
    }
    //---------------------------------------------------------------------------
    int RequestNumberOfPants()
    {
        int Pants;
        cout << "Numbers of Pants: ";
        cin >> Pants;
    
        return Pants;
    }
    //---------------------------------------------------------------------------
    int RequestNumberOfOtherItems()
    {
        int Items;
        cout << "# of other items: ";
        cin >> Items;
    
        return Items;
    }
    //---------------------------------------------------------------------------
    double RequestAmountTended()
    {
        double Amount;
        // Get the amouont tended
        cout << "\n\nAmount tended: $";
        cin >> Amount;
    
        return Amount;
    }
    }
    //---------------------------------------------------------------------------
  7. To use the functions in the main file, click the Main.cpp tab and change it as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Orders.h"
    using namespace std;
    using namespace GeorgetownCleaners;
    //---------------------------------------------------------------------------
    
    #pragma argsused
    void Welcome()
    {
        cout << " - Welcome to Georgetown Cleaning Services -\n";
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        // Declare the number of items
        int NumberOfShirts,
            NumberOfPants,
            NumberOfOtherItems;
        string CustomerName;
    
        // Price of items
        const double PriceShirt = 0.99;
        const double PricePants = 1.95;
        const double PriceOtherItems = 3.25;
        // Declare total prices by category
        double TotalPriceShirt, TotalPricePants, TotalPriceOther;
        double TotalOrder, AmountTended, Difference;
    
        // Welcome the customer
        Welcome();
        CustomerName = GetCustomerName();
    
        NumberOfShirts     = RequestNumberOfShirts();
        NumberOfPants      = RequestNumberOfPants();
        NumberOfOtherItems = RequestNumberOfOtherItems();
    
        // Calculate the total price of each item category
        TotalPriceShirt = NumberOfShirts * PriceShirt;
        TotalPricePants = NumberOfPants * PricePants;
        TotalPriceOther = NumberOfOtherItems * PriceOtherItems;
        TotalOrder      = TotalPriceShirt + TotalPricePants + TotalPriceOther;
    
        // Display the result
        cout << "\n==================================";
        cout << "\n - Georgetown Cleaning Services -";
        cout << "\n----------------------------------";
        cout << "\nCustomer Name: " << CustomerName;
        cout << "\n----------------------------------";
        cout << "\nItem Type\t#\tUnit Price";
        cout << "\nShirts\t\t" << NumberOfShirts << "\t" << PriceShirt;
        cout << "\nPants\t\t"  << NumberOfPants << "\t" << PricePants;
        cout << "\nOthers\t\t" << NumberOfOtherItems << "\t" << PriceOtherItems;
        cout << "\n----------------------------------";
        cout << "\n\tTotal Order: $" << TotalOrder;
        cout << "\n==================================";
    
        AmountTended = RequestAmountTended();
    
        // Calculate the difference for the customer
        Difference = AmountTended - TotalOrder;
    
        // Final message
        cout << "\nThe difference is $" << Difference << "\nThanks";
        
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  8. Test the application. Here is an example:
     
    - Welcome to Georgetown Cleaning Services -
    Enter customer identification
    First Name: Lucy
    Last Name:  Krantz
    Number of shirts: 3
    Numbers of Pants: 2
    # of other items: 5
    
    ==================================
     - Georgetown Cleaning Services -
    ----------------------------------
    Customer Name: Lucy Krantz
    ----------------------------------
    Item Type       #       Unit Price
    Shirts          3       0.99
    Pants           2       1.95
    Others          5       3.25
    ----------------------------------
            Total Order: $23.12
    ==================================
    
    Amount tended: $24
    
    The difference is $0.88
    Thanks
    
    Press any key to continue...
  9. Return to Bcb

Arguments to a Function

Some functions will need to receive a value in order to perform their assignment; some others will not. Some function will have many needs and some others will not. A function’s need is called a parameter. If a function has a lot of such needs, these are its parameters. A parameter is the type of the variable that the function would need to perform its assignment. The most important aspect of a parameter is its data type. This data type is required when the function is declared. When the function is defined, you must specify both the data type and the name of the parameter.

When declaring a function that use one or more parameters, specify each parameter with a data type and an optional name. Here are examples of declaring functions that take parameters:

void SetGender(char a);
double RectangleArea(double L, double W);
char Admission(char Category, double Grade, char g);

The type of value that a function needs is called a parameter. The actual value that would be processed by the function is called an argument. Supplying the value to a function is referred to as passing the argument. When a function is declared, the argument must be specified by its data type. When the function is called, the argument can be passed using the name of a variable of the same type. You can also pass an actual value to the function instead of a variable name.

To use the result of one function inside of another function, that is, to call a function from another function, specify the name of the function and its list of arguments (if any) inside of parentheses; only the name of each argument is needed. Suppose you define the following functions:

//---------------------------------------------------------------------------
double CalculateDiscount(double OriginalPrice, double DiscountRate)
{
    double Amount;

    Amount = OriginalPrice * DiscountRate / 100;
    return Amount;
}
//---------------------------------------------------------------------------
double PriceAfterDiscount(double OriginalPrice, double DiscountAmount)
{
    double After;

    After = OriginalPrice - DiscountAmount;
    return After;
}
//---------------------------------------------------------------------------
double CalculateTaxAmount(double AfterDiscount, double TaxRate)
{
    double Amount;

    Amount = AfterDiscount * TaxRate / 100;
    return Amount;
}
//---------------------------------------------------------------------------
double CalculateNetPrice(double AfterDiscount, double TaxAmount)
{
    double Amount;

    Amount = AfterDiscount + TaxAmount;
    return Amount;
}
//---------------------------------------------------------------------------
void DisplayResult(double OriginalPrice, double DiscountAmount,
                   double AfterDiscount, double TaxAmount, double NetPrice)
{
    cout << "\n\nReceipt";
    cout << "\nOriginal Price:  $" << OriginalPrice;
    cout << "\nDiscount Amount: $" << DiscountAmount;
    cout << "\nAfter Discount:  $" << AfterDiscount;
    cout << "\nTax Amount:      $" << TaxAmount;
    cout << "\nNet Price:       $" << NetPrice;
}
//---------------------------------------------------------------------------

To call such functions from another, you would use:

//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double OriginalPrice, DiscountRate, AfterDiscount, TaxRate;
    double DiscountAmount, TaxAmount, NetPrice;

    OriginalPrice = RequestOriginalPrice();
    DiscountRate  = RequestDiscountRate();
    TaxRate       = RequestTaxRate();

    DiscountAmount = CalculateDiscount(OriginalPrice, DiscountRate);
    AfterDiscount  = PriceAfterDiscount(OriginalPrice, DiscountAmount);
    TaxAmount      = CalculateTaxAmount(AfterDiscount, TaxRate);
    NetPrice       = CalculateNetPrice(AfterDiscount, TaxAmount);

    DisplayResult(OriginalPrice, DiscountAmount,
                  AfterDiscount, TaxAmount, NetPrice);

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

When declaring a function, the compiler does not require that you supply a name for each argument, it only needs to know the type of argument(s) and the number of arguments a function takes. This information is completely provided by the presence of a data type. This means you can declare your functions as follows:

//---------------------------------------------------------------------------
double CalculateDiscount(double, double);
double PriceAfterDiscount(double, double);
double CalculateTaxAmount(double, double);
double CalculateNetPrice(double, double);
void DisplayResult(double, double, double, double, double);
//---------------------------------------------------------------------------

When defining functions that have been declared as done above, you must provide a name for each argument that you intend to use.

The compiler also does not care about the name you give an argument when declaring a function. When implementing the function, you just have to remember to use the same name(s) included in the parentheses of the function. Here are examples of functions that take arguments:Here are examples:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;

#pragma hdrstop

//---------------------------------------------------------------------------
#pragma argsused

double CalculateDiscount(double, double);
double PriceAfterDiscount(double, double);
double CalculateTaxAmount(double, double);
double CalculateNetPrice(double, double);
void DisplayResult(double, double, double, double, double);
//---------------------------------------------------------------------------
double RequestOriginalPrice()
{
    double Price;

    cout << "Enter the original price: $";
    cin >> Price;
    return Price;
}
//---------------------------------------------------------------------------
double RequestDiscountRate()
{
    double Discount;

    cout << "Enter discount rate(0.00 to 100.00): ";
    cin >> Discount;
    return Discount;
}
//---------------------------------------------------------------------------
double RequestTaxRate()
{
    double Tax;

    cout << "Enter the tax rate(0.00 to 100.00): ";
    cin >> Tax;
    return Tax;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double OriginalPrice, DiscountRate, AfterDiscount, TaxRate;
    double DiscountAmount, TaxAmount, NetPrice;

    OriginalPrice = RequestOriginalPrice();
    DiscountRate  = RequestDiscountRate();
    TaxRate       = RequestTaxRate();

    DiscountAmount = CalculateDiscount(OriginalPrice, DiscountRate);
    AfterDiscount  = PriceAfterDiscount(OriginalPrice, DiscountAmount);
    TaxAmount      = CalculateTaxAmount(AfterDiscount, TaxRate);
    NetPrice       = CalculateNetPrice(AfterDiscount, TaxAmount);

    DisplayResult(OriginalPrice, DiscountAmount,
                  AfterDiscount, TaxAmount, NetPrice);

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
double CalculateDiscount(double Original, double Rate)
{
    double Amount;

    Amount = Original * Rate / 100;
    return Amount;
}
//---------------------------------------------------------------------------
double PriceAfterDiscount(double Original, double Discount)
{
    double After;

    After = Original - Discount;
    return After;
}
//---------------------------------------------------------------------------
double CalculateTaxAmount(double Discount, double Rate)
{
    double Amount;

    Amount = Discount * Rate / 100;
    return Amount;
}
//---------------------------------------------------------------------------
double CalculateNetPrice(double Discount, double TaxAmt)
{
    double Amount;

    Amount = Discount + TaxAmt;
    return Amount;
}
//---------------------------------------------------------------------------
void DisplayResult(double OrigPrice, double DiscAmt,
                   double Discount, double TaxAmt, double FinalPrice)
{
    cout << "\n\nReceipt";
    cout << "\nOriginal Price:  $" << OrigPrice;
    cout << "\nDiscount Amount: $" << DiscAmt;
    cout << "\nAfter Discount:  $" << Discount;
    cout << "\nTax Amount:      $" << TaxAmt;
    cout << "\nNet Price:       $" << FinalPrice;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Enter the original price: $100
Enter discount rate(0.00 to 100.00): 25
Enter the tax rate(0.00 to 100.00): 5.75


Receipt
Original Price:  $100
Discount Amount: $25
After Discount:  $75
Tax Amount:      $4.3125
Net Price:       $79.3125

Press any key to continue...

As seen already, the return keyword is used to return an appropriate value from a non-void function. In fact, the item on the right side of the return keyword could be a simple value or a complete expression. Fortunately, the compiler is able to evaluate this item and find out whether it is conform to the return type on the left side of the function name. For this reason, inside of the function that performs a calculation and returns its result, you do not have to first declare a variable that would hold the return value; as long as you provide an appropriate value or expression on the right side of the return keyword, the compiler would be satisfied. Therefore, the above functions could have been implemented as follows:

//---------------------------------------------------------------------------
double CalculateDiscount(double Original, double Rate)
{
    return Original * Rate / 100;
}
//---------------------------------------------------------------------------
double PriceAfterDiscount(double Original, double Discount)
{
    return Original - Discount;
}
//---------------------------------------------------------------------------
double CalculateTaxAmount(double Discount, double Rate)
{
    return Discount * Rate / 100;
}
//---------------------------------------------------------------------------
double CalculateNetPrice(double Discount, double TaxAmt)
{
    return Discount + TaxAmt;
}
//---------------------------------------------------------------------------
 

Practical Learning Practical Learning: Passing Arguments

  1. To experiment with passing arguments to functions, click the Orders.h tab and declare the following functions:
     
    //---------------------------------------------------------------------------
    #ifndef OrdersH
    #define OrdersH
    #include <iostream>
    #include <string>
    using namespace std;
    //---------------------------------------------------------------------------
    namespace GeorgetownCleaners
    {
    // Price of items
    const double PriceShirt = 0.99;
    const double PricePants = 1.95;
    const double PriceOtherItems = 3.25;
    
    string GetCustomerName();
    int RequestNumberOfShirts();
    int RequestNumberOfPants();
    int RequestNumberOfOtherItems();
    double GetTaxRate();
    double CalculatePriceShirts(int Shirts, double Price);
    double CalculatePricePants(int Pants, double Price);
    double CalculatePriceOthers(int Others, double Price);
    double CalculateTotalOrder(double Shirts, double Pants, double Others);
    double CalculateTaxAmount(double Total, double Tax);
    double CalculateTotalPrice(double Total, double Tax);
    void DisplayReceipt(string Name, int Shirts, int Pants,
                        int Others, double Tax, double Total);
    }
    //---------------------------------------------------------------------------
    #endif
  2. Click the Orders.cpp tab and implement the functions as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Orders.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace GeorgetownCleaners
    {
    string GetCustomerName()
    {
        string FirstName, LastName;
    
        cout << "Enter customer identification\n";
        cout << "First Name: "; cin >> FirstName;
        cout << "Last Name:  "; cin >> LastName;
    
        return FirstName + " " + LastName;
    }
    //---------------------------------------------------------------------------
    int RequestNumberOfShirts()
    {
        int Shirts;
        cout << "Number of shirts: ";
        cin >> Shirts;
    
        return Shirts;
    }
    //---------------------------------------------------------------------------
    int RequestNumberOfPants()
    {
        int Pants;
        cout << "Numbers of Pants: ";
        cin >> Pants;
    
        return Pants;
    }
    //---------------------------------------------------------------------------
    int RequestNumberOfOtherItems()
    {
        int Items;
    
        cout << "# of other items: ";
        cin >> Items;
        return Items;
    }
    //---------------------------------------------------------------------------
    double GetTaxRate()
    {
        double Rate;
    
        cout << "Enter the tax rate (such as 5.75): ";
        cin >> Rate;
        return Rate;
    }
    //---------------------------------------------------------------------------
    double CalculatePriceShirts(int Shirts, double Price)
    {
        return Shirts * Price;
    } 
    //---------------------------------------------------------------------------
    double CalculatePricePants(int Pants, double Price)
    {  
        return Pants * Price;
    }
    //---------------------------------------------------------------------------
    double CalculatePriceOthers(int Others, double Price)
    {         
        return Others * Price;
    }
    //---------------------------------------------------------------------------
    double CalculateTotalOrder(double Shirts, double Pants, double Others)
    {
        return Shirts + Pants + Others;
    }
    //---------------------------------------------------------------------------
    double CalculateTaxAmount(double Total, double Rate)
    {
        return Total * Rate / 100;
    }
    //---------------------------------------------------------------------------
    double CalculateTotalPrice(double Total, double Tax)
    {
        return Total + Tax;
    }
    //---------------------------------------------------------------------------
    void DisplayReceipt(string CustName, int Shirts,
                        int Pants, int Others, double Tax, double Total)
    {
        // Display the result
        cout << "\n======================================";
        cout << "\n - Georgetown Cleaning Services -";
        cout << "\n--------------------------------------";
        cout << "\nCustomer Name: " << CustName;
        cout << "\n--------------------------------------";
        cout << "\nItem Type\t#\tUnit\tTotal";
        cout << "\nShirts\t\t" << Shirts << "\t" << PriceShirt
             << "\t" << CalculatePriceShirts(Shirts, PriceShirt);
        cout << "\nPants\t\t"  << Pants << "\t" << PricePants
             << "\t" << CalculatePricePants(Pants, PricePants);
        cout << "\nOthers\t\t" << Others << "\t" << PriceOtherItems
             << "\t" << CalculatePriceOthers(Others, PriceOtherItems);
        cout << "\n--------------------------------------";
        cout << "\n\tTax Amount:  $" << Tax;
        cout << "\n\tTotal Order: $" << Total;
        cout << "\n======================================";
    }
    }
    //---------------------------------------------------------------------------
  3. To test the new functions, click the Main.cpp tab and change the file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Orders.h"
    using namespace std;
    using namespace GeorgetownCleaners;
    //---------------------------------------------------------------------------
    
    #pragma argsused
    void Welcome()
    {
        cout << " - Welcome to Georgetown Cleaning Services -\n";
    }
    //---------------------------------------------------------------------------
    double RequestAmountTended()
    {
        double Amount;
        // Get the amount tended
        cout << "\n\nAmount tended: $";
        cin >> Amount;
    
        return Amount;
    }
    //---------------------------------------------------------------------------
    double CalculateAmountOwed(double Tended, double Total)
    {
        return Tended - Total;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {                // Declare the number of items
        int NumberOfShirts,
            NumberOfPants,
            NumberOfOtherItems;
        string CustomerName;
    
        // Declare total prices by category
        double TotalPriceShirts, TotalPricePants, TotalPriceOthers;
        double TotalOrder, TaxRate, TaxAmount, NetPrice;
        double AmountTended, Difference;
    
        // Welcome the customer
        Welcome();
        CustomerName = GetCustomerName();
    
        NumberOfShirts     = RequestNumberOfShirts();
        NumberOfPants      = RequestNumberOfPants();
        NumberOfOtherItems = RequestNumberOfOtherItems();
        TaxRate            = GetTaxRate();
    
        // Calculate the total price of each item category
        TotalPriceShirts = CalculatePriceShirts(NumberOfShirts, PriceShirt);
        TotalPricePants  = CalculatePricePants(NumberOfPants, PricePants);
        TotalPriceOthers = CalculatePriceOthers(NumberOfOtherItems,
                                                PriceOtherItems);
        TotalOrder       = CalculateTotalOrder(TotalPriceShirts,
                                               TotalPricePants,
                                               TotalPriceOthers);
        TaxAmount        = CalculateTaxAmount(TotalOrder, TaxRate);
        NetPrice         = CalculateTotalPrice(TotalOrder, TaxAmount);
    
        // Display the result
        DisplayReceipt(CustomerName, NumberOfShirts, NumberOfPants,
                       NumberOfOtherItems, TaxAmount, NetPrice);
    
        AmountTended = RequestAmountTended();
        // Calculate the difference for the customer
        Difference = CalculateAmountOwed(AmountTended, TotalOrder);
    
        // Final message
        cout << "\nThe difference is $" << Difference << "\nThanks";
        
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  4. Test the program. Here is an example:
     
    - Welcome to Georgetown Cleaning Services -
    Enter customer identification
    First Name: Serge
    Last Name:  Macomb
    Number of shirts: 5
    Numbers of Pants: 2
    # of other items: 2
    Enter the tax rate (such as 5.75): 5.55
    
    ======================================
     - Georgetown Cleaning Services -
    --------------------------------------
    Customer Name: Serge Macomb
    --------------------------------------
    Item Type       #       Unit    Total
    Shirts          5       0.99    4.95
    Pants           2       1.95    3.9
    Others          2       3.25    6.5
    --------------------------------------
            Tax Amount:  $0.851925
            Total Order: $16.2019
    ======================================
    
    Amount tended: $20
    
    The difference is $4.65
    Thanks
    
    Press any key to continue...
  5. After testing the program, return to Bcb.

Inline Functions

When you call a function B() from function A(), function A() sends a request and must get to Function B(). This is sometimes cumbersome for a long function that is calling a small or short function. Whenever your program includes a small function, C++ allows you to include such a function where it is being called. When function B() calls function A(), instead of sending a request to function A(), the compiler would include a copy of function A() into function B() where it is being called. Such a function (function A()) is qualified inline.

To declare a function as inline, use the inline keyword on the left side of the function. Here is an example:

inline double CalculateDiscount(double, double);

When defining the function, use the inline keyword in the same way. Here is an example that makes use of an inline function:

//---------------------------------------------------------------------------
inline double CalculateDiscount(double Original, double Rate)
{
    double Amount;

    Amount = Original * Rate / 100;
    return Amount;
}
//---------------------------------------------------------------------------
 

Practical Learning Practical Learning: Using inline Functions

  1. To use inline functions, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Orders.h"
    using namespace std;
    using namespace GeorgetownCleaners;
    //---------------------------------------------------------------------------
    
    #pragma argsused
    void Welcome()
    {
        cout << " - Welcome to Georgetown Cleaning Services -\n";
    }
    //---------------------------------------------------------------------------
    inline double RequestAmountTended()
    {
        double Amount;
        // Get the amount tended
        cout << "\n\nAmount tended: $";
        cin >> Amount;
    
        return Amount;
    }
    //---------------------------------------------------------------------------
    inline double CalculateAmountOwed(double Tended, double Total)
    {
        return Tended - Total;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {                
        . . . No Change
        
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Test the program and return to Bcb

Static Variables

Consider the following program:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
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(int argc, char* argv[])
{
    Starter(2);
    Starter(2);
    Starter(2);
    Starter(2);

    cout << "Press any key continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

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

Press any key continue...

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 presence of the function. If you want a locally declared variable to keep its changed value when its host function is exited, you can declare such a variable as static.

To declare a static variable, type the keyword static 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;
}
//---------------------------------------------------------------------------

You should always initialize a static variable before using it; that is, 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

Press any key continue...

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>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
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(int argc, char* argv[])
{
    Starter(2);
    Starter(5);
    Starter(14);
    Starter(25);

    cout << "Press any key continue...";
    getch();
    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

Press any key continue...
 

Passing Arguments to Registers

All the variables that we have used so far were declared in, and passed to, the random memory (RAM). Once a variable is declared and “put” in the memory, whenever it is involved in a calculation or assignment, the microprocessor sends a request to the memory to retrieve the value of the variable.

The Central Processing Unit (CPU), also called the microprocessor, has its own memory. The microprocessor is made of memory cells called registers. Unlike the memory in the RAM, the access of the memory in the microprocessor is more precise; so precise that the registers are referred to by using their names. Some of the most commonly used registers (also called general purpose registers) are called EAX, EBX, ECX, EDX, ESI, etc. These registers are mostly used in the Assembly Language for low-level programming. Using registers allows the programmer to write assignments directly destined for the microprocessor. The assignments and operations in the Assembly language are called instructions. When instructions are used by registers, the processing of the program is fast because the microprocessor does not have to retrieve the values of the variables in the RAM; these values, since existing in the registers, are readily available.

Borland C++ Builder (and most popular compilers) allow you to include Assembly Language code in your program. Using this feature, you can write a section or sections of Assembly language. A section that has Assembly code starts with __asm followed by some other techniques. When the compiler encounters this keyword, it knows that the subsequent code would be in Assembly language and it would treat it accordingly. For example, instead of performing a calculation in the RAM, the following program will assign values to two integer variables, namely Number1 and Number2, then it calculate their sum of those two numbers and stores the result in another variable called Result. After the calculation, the Assembly section sends the result back to the C++ compiler to display the variables and their values:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Number1, Number2, Result;

    __asm
    {
        MOV Number1, 248 // Initialize Number1
        MOV Number2, 405 // Initialize Number2
        MOV EAX, Number1 // Put the value of Number1 in the EAX register
        ADD EAX, Number2 // Add the value of Number2 to the content of EAX
        MOV Result, EAX  // Put the content of EAX into Result
    }                    // That's it

    cout << "Number1 = " << Number1 << endl;
    cout << "Number2 = " << Number2 << endl;
    cout << "\nAfter adding Number1 to Number2," << endl;
    cout << "Result  = " << Result << endl;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Number1 = 248
Number2 = 405

After adding Number1 to Number2,
Result  = 653

Press any key to continue...

C++ Builder ships with a version of Assembly language so that if you are interested in adding low-level code, you do not have to purchase an assembler. In fact, C++ installs TASM (known as Turbo Assembler), the award wining Assembler from Borland. This means that, if you want to learn Assembly, you may not have to purchase it anymore (unfortunately, it is not documented). Alternatively, the C++ Builder compiler has its own Assembler known as Inline Assembly. This allows you to embed Assembly code in your programs.

The ability for C++ Builder to recognize Assembly code allows you to pass arguments to registers. For example, you can pass arguments to the EAX, EBX, ECX, or EDX, etc registers to speed the compilation process. Fortunately, you do not need to learn Assembly language (although you are encouraged to do so) to speed your code in C++ Builder. As an alternative, you can use the __fastcall keyword whenever you would have passed arguments in registers.

The syntax for using the __fastcall keyword is:

ReturnType __fastcall FunctionName(Arguments);

Whenever you decide to use __fastcall, use it both when declaring and when defining the function. As an introductory example of using __fastcall, the following program uses two functions. The first function, GetFullName() requests an employee’s first and last names, then it returns the full name. Since this function is defined before being used, it was not declared in the main() function. The second function, because defined after main() (this was done on purpose), is declared in main() prior to using it. Both functions use the __fastcall keyword. Notice that both functions have their arguments also passed by reference. Here is the complete program:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
string __fastcall GetFullName(string fn, string ln)
{
    string FN;

    cout << "First Name: ";
    cin >> fn;
    cout << "Last Name: ";
    cin >> ln; FN = fn + " " + ln;

    return FN;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    string FirstName, LastName, FullName;
    double Hours, HourlySalary, WeeklySalary;
    void __fastcall GetHours(double& x, double& y);

    cout << "Enter information about the employee\n";
    FullName = GetFullName(FirstName, LastName);
    GetHours(Hours, HourlySalary);
    WeeklySalary = Hours * HourlySalary;

    cout << "\nEmployee's Records";
    cout << "\nFull Name: " << FullName;
    cout << "\nWeekly Hours: " << Hours;
    cout << "\nHourly Salary: $" << HourlySalary;
    cout << "\nWeekly Wages: $" << WeeklySalary;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall GetHours(double& h, double& s)
{
    cout << "Total hours for the week: ";
    cin >> h;
    cout << "Hourly Salary: $";
    cin >> s;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Enter information about the employee
First Name: Henry
Last Name: Ndjakou
Total hours for the week: 35.50
Hourly Salary: $12.55

Employee's Records
Full Name: Henry Ndjakou
Weekly Hours: 35.5
Hourly Salary: $12.55
Weekly Wages: $445.525

Press any key to continue...
 

Practical Learning Practical Learning: Using __fastcall

  1. To use __fastcall, change Orders.h file as follows:
     
    //---------------------------------------------------------------------------
    #ifndef OrdersH
    #define OrdersH
    #include <iostream>
    #include <string>
    using namespace std;
    //---------------------------------------------------------------------------
    namespace GeorgetownCleaners
    {
    // Price of items
    const double PriceShirt = 0.99;
    const double PricePants = 1.95;
    const double PriceOtherItems = 3.25;
    
    string __fastcall GetCustomerName();
    int __fastcall RequestNumberOfShirts();
    int __fastcall RequestNumberOfPants();
    int __fastcall RequestNumberOfOtherItems();
    double __fastcall GetTaxRate();
    inline double __fastcall CalculatePriceShirts(int Shirts, double Price);
    inline double __fastcall CalculatePricePants(int Pants, double Price);
    inline double __fastcall CalculatePriceOthers(int Others, double Price);
    inline double __fastcall CalculateTotalOrder(double Shirts, double Pants,
                                                 double Others);
    inline double __fastcall CalculateTaxAmount(double Total, double Tax);
    inline double __fastcall CalculateTotalPrice(double Total, double Tax);
    void __fastcall DisplayReceipt(string Name, int Shirts, int Pants,
                                   int Others, double Tax, double Total);
    }
    //---------------------------------------------------------------------------
    #endif
  2. change the functions in the Orders.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Orders.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace GeorgetownCleaners
    {
    string __fastcall GetCustomerName()
    {
        string FirstName, LastName;
    
        cout << "Enter customer identification\n";
        cout << "First Name: "; cin >> FirstName;
        cout << "Last Name:  "; cin >> LastName;
    
        return FirstName + " " + LastName;
    }
    //---------------------------------------------------------------------------
    int __fastcall RequestNumberOfShirts()
    {
        int Shirts;
        cout << "Number of shirts: ";
        cin >> Shirts;
    
        return Shirts;
    }
    //---------------------------------------------------------------------------
    int __fastcall RequestNumberOfPants()
    {
        int Pants;
        cout << "Numbers of Pants: ";
        cin >> Pants;
    
        return Pants;
    }
    //---------------------------------------------------------------------------
    int __fastcall RequestNumberOfOtherItems()
    {
        int Items;
    
        cout << "# of other items: ";
        cin >> Items;
        return Items;
    }
    //---------------------------------------------------------------------------
    double __fastcall GetTaxRate()
    {
        double Rate;
    
        cout << "Enter the tax rate (such as 5.75): ";
        cin >> Rate;
        return Rate;
    }
    //---------------------------------------------------------------------------
    inline double __fastcall CalculatePriceShirts(int Shirts, double Price)
    {
        return Shirts * Price;
    } 
    //---------------------------------------------------------------------------
    inline double __fastcall CalculatePricePants(int Pants, double Price)
    {  
        return Pants * Price;
    }
    //---------------------------------------------------------------------------
    inline double __fastcall CalculatePriceOthers(int Others, double Price)
    {         
        return Others * Price;
    }
    //---------------------------------------------------------------------------
    inline double __fastcall CalculateTotalOrder(double Shirts,
                                                 double Pants, double Others)
    {
        return Shirts + Pants + Others;
    }
    //---------------------------------------------------------------------------
    inline double __fastcall CalculateTaxAmount(double Total, double Rate)
    {
        return Total * Rate / 100;
    }
    //---------------------------------------------------------------------------
    inline double __fastcall CalculateTotalPrice(double Total, double Tax)
    {
        return Total + Tax;
    }
    //---------------------------------------------------------------------------
    void __fastcall DisplayReceipt(string CustName, int Shirts,
                        int Pants, int Others, double Tax, double Total)
    {
        // Display the result
        cout << "\n======================================";
        cout << "\n - Georgetown Cleaning Services -";
        cout << "\n--------------------------------------";
        cout << "\nCustomer Name: " << CustName;
        cout << "\n--------------------------------------";
        cout << "\nItem Type\t#\tUnit\tTotal";
        cout << "\nShirts\t\t" << Shirts << "\t" << PriceShirt
             << "\t" << CalculatePriceShirts(Shirts, PriceShirt);
        cout << "\nPants\t\t"  << Pants << "\t" << PricePants
             << "\t" << CalculatePricePants(Pants, PricePants);
        cout << "\nOthers\t\t" << Others << "\t" << PriceOtherItems
             << "\t" << CalculatePriceOthers(Others, PriceOtherItems);
        cout << "\n--------------------------------------";
        cout << "\n\tTax Amount:  $" << Tax;
        cout << "\n\tTotal Order: $" << Total;
        cout << "\n======================================";
    }
    }
    //---------------------------------------------------------------------------
  3. In the same way, change the functions in the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Orders.h"
    using namespace std;
    using namespace GeorgetownCleaners;
    //---------------------------------------------------------------------------
    
    #pragma argsused
    void __fastcall Welcome()
    {
        cout << " - Welcome to Georgetown Cleaning Services -\n";
    }
    //---------------------------------------------------------------------------
    inline double __fastcall RequestAmountTended()
    {
        double Amount;
        // Get the amount tended
        cout << "\n\nAmount tended: $";
        cin >> Amount;
    
        return Amount;
    }
    //---------------------------------------------------------------------------
    inline double __fastcall CalculateAmountOwed(double Tended, double Total)
    {
        return Tended - Total;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {                // Declare the number of items
        int NumberOfShirts,
            NumberOfPants,
            NumberOfOtherItems;
        string CustomerName;
    
        // Declare total prices by category
        double TotalPriceShirts, TotalPricePants, TotalPriceOthers;
        double TotalOrder, TaxRate, TaxAmount, NetPrice;
        double AmountTended, Difference;
    
        // Welcome the customer
        Welcome();
        CustomerName = GetCustomerName();
    
        NumberOfShirts     = RequestNumberOfShirts();
        NumberOfPants      = RequestNumberOfPants();
        NumberOfOtherItems = RequestNumberOfOtherItems();
        TaxRate            = GetTaxRate();
    
        // Calculate the total price of each item category
        TotalPriceShirts = CalculatePriceShirts(NumberOfShirts, PriceShirt);
        TotalPricePants  = CalculatePricePants(NumberOfPants, PricePants);
        TotalPriceOthers = CalculatePriceOthers(NumberOfOtherItems,
                                                PriceOtherItems);
        TotalOrder       = CalculateTotalOrder(TotalPriceShirts,
                                               TotalPricePants,
                                               TotalPriceOthers);
        TaxAmount        = CalculateTaxAmount(TotalOrder, TaxRate);
        NetPrice         = CalculateTotalPrice(TotalOrder, TaxAmount);
    
        // Display the result
        DisplayReceipt(CustomerName, NumberOfShirts, NumberOfPants,
                       NumberOfOtherItems, TaxAmount, NetPrice);
    
        AmountTended = RequestAmountTended();
        // Calculate the difference for the customer
        Difference = CalculateAmountOwed(AmountTended, TotalOrder);
    
        // Final message
        cout << "\nThe difference is $" << Difference << "\nThanks";
        
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  4. Test the program and return to Bcb

Function Overloading

We saw earlier that, when declaring a function, the compiler needs to know only the name of the function, its return type and its type(s) of argument(s), if any.  We saw that, based on this ability of the C++ language, functions could be declared as follows:

//---------------------------------------------------------------------------
double CalculateDiscount(double, double);
double PriceAfterDiscount(double, double);
double CalculateTaxAmount(double, double);
double CalculateNetPrice(double, double);
void   DisplayResult(double, double, double, double, double);
//---------------------------------------------------------------------------

The name of a function, its return type, and its list of arguments, if any, is called the function's signature. This signature gives complete information to the compiler regarding each function. The compiler needs this information about each function because it creates a table (called a virtual table) of all functions used in a particular file whether it is a header file or a source file. When creating this table, the compiler assigns a unique identification (like somebody's driver's license) to each function, using the function's name, its return type, and its argument(s) (this allows the compiler to perform name mangling).

When creating this table, the compiler uses each function's name and its argument(s), if any:

  • If two functions have different names, they would have different identifications, regardless of their argument(s), if any
  • If two functions have the exact same name and exact same type(s) or argument(s), both functions would have the same identification, which would result into a conflict (of course, you can use namespaces to prevent this conflict)
  • If two functions have the exact same name but different argument(s), either by the number of arguments or the type(s) of argument(s), they would have different identifications. 

The ability for two functions to have the exact same name but differ either by their type(s) of argument(s) or by their number of argument(s) allows the compiler to distinguish them. This is the foundation of Function Overloading: Function Overloading is the ability to have various functions that have the same name but different arguments, either by the number of arguments of each function or by the types of arguments of each function.

Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
// Area of a square
float Area(float Side)
{
    return (Side * Side);
}
//---------------------------------------------------------------------------
// Area of a rectangle
float Area(float Length, float Width)
{
    return (Length * Width);
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    float s, l, w;

    s = 15.25;
    l = 28.12;
    w = 10.35;

    cout << "The rea of the square is " << Area(s);
    cout << "\nThe area of the rectangle is " << Area(l, w);

    cout << "\n\nPress any key to continue...";


    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is the result of running the program:

The rea of the square is 232.562
The area of the rectangle is 291.042

Press any key to continue...

You can also declare overloaded functions as inline and/or __fastcall.

Practical Learning Practical Learning: Overloading Functions

The moment of inertia is the ability of of a beam to resist bending. It is calculated with regard to the cross section of the beam. Because it depends on the type of section of the beam, its calculation also depends on the type of section of the beam: rectangular, triangular, circular, etc. In this exercise, we will review different formulas used to calculate the moment of inertia. Since this exercise is for demonstration purposes, you do not need to be a Science Engineering major to understand it. The most important thing here is the implementation of overloaded functions.

  1. Create a new C++ console project using the Console Wizard
  2. Save everything in a new folder called Moment Of Inertia1
  3. Save the unit as Main.cpp and save the project as MomentOfInertia
  4. Change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {            
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  5. Create a new unit and save it as Inertia
  6. Here are the formulas to calculate the moment of inertia of a beam with a rectangular section, depending on the axis considered:
     
    Function Overloading: Rectangle

    To calculate the moment of inertia with regard to the X axis, in the Inertia.h file, declare the following function:

    //---------------------------------------------------------------------------
    #ifndef InertiaH
    #define InertiaH
    //---------------------------------------------------------------------------
    namespace Geometry
    {
    double MomentOfInertia(double b, double h);
    }
    //---------------------------------------------------------------------------
    #endif
  7. Implement the function in the Inertia.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Inertia.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace Geometry
    {
    double MomentOfInertia(double b, double h)
    {
        return b * h * h * h / 3;
    }
    }
    //---------------------------------------------------------------------------
  8. Call the function in the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Inertia.h"
    //---------------------------------------------------------------------------
    using namespace std;
    using namespace Geometry;
    #pragma argsused
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        double Base, Height;
    
        cout << "Enter the dimensions of the Rectangle\n";
        cout << "Base: ";
        cin >> Base;
        cout << "Height: ";
        cin >> Height;
    
        cout << "\nMoment of inertia with regard to the X axis: ";
        cout << "I = " << MomentOfInertia(Base, Height) << "mm";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  9. Test the function. Here is an example:
     
    Enter the dimensions of the Rectangle
    Base: 3.25
    Height: 6.15
    
    Moment of inertia with regard to the X axis: I = 251.992mm
    
    Press any key to continue...
  10. After testing the function, return to Bcb
  11. To make the function __fastcall, in the Inertia.h file, start the declaration of the function with the __fastcall keyword as follows:
     
    //---------------------------------------------------------------------------
    #ifndef InertiaH
    #define InertiaH
    //---------------------------------------------------------------------------
    namespace Geometry
    {
    double __fastcall MomentOfInertia(double b, double h);
    }
    //---------------------------------------------------------------------------
    #endif
  12. In the Inertia.cpp file, add the __fastcall keyword as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Inertia.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace Geometry
    {
    double __fastcall MomentOfInertia(double b, double h)
    {
        return b * h * h * h / 3;
    }
    }
    //---------------------------------------------------------------------------
  13. Test the program and return to Bcb
  14. Here are the formulas to calculate the moment of inertia for a semi-circle:
     
    Function Overloading: Circle

    A circle and thus a semi-circle requires only a radius. Since the other version of the MomentOfInertia() function requires two arguments, we can overload it by providing only one argument, the radius.
    To calculate the moment of inertia with regard to the X or base axis, in the Inertia.h file, overload the MomentOfInertia() function as follows:

    //---------------------------------------------------------------------------
    #ifndef InertiaH
    #define InertiaH
    //---------------------------------------------------------------------------
    namespace Geometry
    {
    const double PI = 3.14159;
    // Rectangle
    double __fastcall MomentOfInertia(double b, double h);
    // Semi-Circle
    double __fastcall MomentOfInertia(double R);
    }
    //---------------------------------------------------------------------------
    #endif
  15. In the Inertia.h file, implement the overloaded function as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Inertia.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace Geometry
    {
    //---------------------------------------------------------------------------
    // Rectangle
    double __fastcall MomentOfInertia(double b, double h)
    {
        return b * h * h * h / 3;
    }
    //---------------------------------------------------------------------------
    // Semi-Circle
    double __fastcall MomentOfInertia(double R)
    {
        return R * R * R * R * PI/ 8;
    
    }
    //---------------------------------------------------------------------------
    }
    //---------------------------------------------------------------------------
  16. Call the functions in the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Inertia.h"
    //---------------------------------------------------------------------------
    using namespace std;
    using namespace Geometry;
    #pragma argsused
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        double Base, Height, Radius;
    
        cout << "Enter the dimensions of the Rectangle\n";
        cout << "Base: ";
        cin >> Base;
        cout << "Height: ";
        cin >> Height;
    
        cout << "Moment of inertia with regard to the X axis: ";
        cout << "I = " << MomentOfInertia(Base, Height) << "mm";
    
        cout << "\n\nEnter the radius: ";
        cin >> Radius;
        cout << "Moment of inertia of a semi-circle with regard to the X axis: ";
        cout << "I = " << MomentOfInertia(Radius) << "mm\n";
    
        cout << "\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  17. Test the program. Here is an example:
     
    Enter the dimensions of the Rectangle
    Base: 3.25
    Height: 2.75
    Moment of inertia with regard to the X axis: I = 22.5299mm
    
    Enter the radius: 4.15
    Moment of inertia of a semi-circle with regard to the X axis: I = 116.48mm
    
    Press any key to continue...
  18. After testing the program, return to Bcb
  19. Here are the formulas to calculate the moment of inertia of a triangle:
     
    Function Overloading: Triangle

    As you can see, the rectangle and the triangle are using the same dimension types. This means that, we can provide only the same kinds of arguments, the base and the height, to calculate the moment of inertia. In order to overload the MomentOfInertia() function, we will add an argument that will never be used; this argument will serve only as a “witness” to set the difference between both versions of the function. This “witness” argument can be anything: an integer, a character, a string, a float, etc. For our example, we will make it a simple integer. To use the version applied to the triangle, we will provide this argument to overload the MomentOfInertia() function. When called with only two arguments, the rectangle version will apply.
    To calculate the moment of inertia with regard to the X axis, in the Inertia.h file, overload the MomentOfInertia function as follows:

    //---------------------------------------------------------------------------
    #ifndef InertiaH
    #define InertiaH
    //---------------------------------------------------------------------------
    namespace Geometry
    {
    const double PI = 3.14159;
    // Rectangle
    
    double __fastcall MomentOfInertia(double b, double h);
    // Semi-Circle
    double __fastcall MomentOfInertia(double R);
    // Triangle
    double __fastcall MomentOfInertia(double b, double h, int);
    }
    //---------------------------------------------------------------------------
    #endif
  20. In the Inertia.cpp file, implement the function as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "Inertia.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    namespace Geometry
    {
    //---------------------------------------------------------------------------
    // Rectangle
    double __fastcall MomentOfInertia(double b, double h)
    {
        return b * h * h * h / 3;
    }
    //---------------------------------------------------------------------------
    // Semi-Circle
    double __fastcall MomentOfInertia(double R)
    {
        return R * R * R * R * PI/ 8;
    }
    //---------------------------------------------------------------------------
    // Triangle
    double __fastcall MomentOfInertia(double b, double h, int)
    {
        return b * h * h * h / 12;
    }
    //---------------------------------------------------------------------------
    }
    //---------------------------------------------------------------------------
  21. In the Main.cpp file, call the function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    #pragma hdrstop
    #include "Inertia.h"
    //---------------------------------------------------------------------------
    using namespace std;
    using namespace Geometry;
    #pragma argsused
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        double Base = 7.74,
               Height = 14.38,
               Radius = 12.42;
    
        cout << "Rectangle\n"
             << "Moment of inertia with regard to the X axis: ";
        cout << "I = " << MomentOfInertia(Base, Height) << "mm\n\n";
    
        cout << "Semi-Circle\n"
             << "Moment of inertia with regard to the X axis: ";
        cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";
    
        cout << "Enter the dimensions of the triangle\n";
        cout << "Base: ";
        cin >> Base;
        cout << "Height: ";
        cin >> Height;
        cout << "\nTriangle\n"
             << "Moment of inertia with regard to the X axis: ";
        cout << "I = " << MomentOfInertia(Base, Height, 1) << "mm\n";
    
        cout << "\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  22. Test the program. Here is an example:
     
    Rectangle
    Moment of inertia with regard to the X axis: I = 7671.78mm
    
    Semi-Circle
    Moment of inertia with regard to the X axis: I = 9344.28mm
    
    Enter the dimensions of the triangle
    Base: 4.55
    Height: 2.75
    
    Triangle
    Moment of inertia with regard to the X axis: I = 7.88548mm
    
    Press any key to continue...
  23. After testing the program, return to Bcb

Conditional Statements and Functions

 

Using Conditions in Functions

 
The use of functions in a program allows you to isolate assignments and confine them to appropriate entities. While the functions take care of specific requests, you should provide them with conditional statements to validate what these functions are supposed to do. There are no set rules to the techniques involved; everything depends on the tasks at hand. Once again, you will have to choose the right tools for the right job. To make effective use of functions, you should be very familiar with different data types because you will need to return the right value.

The ergonomic program we have been writing so far needs to check different things including answers from the user in order to proceed. These various assignments can be given to functions that would simply hand the results to the main() function that can, in turn, send these results to other functions for further processing. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused

//---------------------------------------------------------------------------
#define Or ||
#define And &&
//---------------------------------------------------------------------------
char __fastcall GetPosition()
{
	char Position;

	do {
		cout << "Are you sitting down now(y/n)? ";
		cin >> Position;

		if( Position != 'y' And Position != 'Y' And
			Position != 'n' And Position != 'N' )
			cout << "Invalid Answer\n";
	} while( Position != 'y' And Position != 'Y' And
			 Position != 'n' And Position != 'N' );

	return Position;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    char Position;

    Position = GetPosition();
    if( Position == 'n' Or Position == 'N' )
        cout << "\nCould you please sit down for the next exercise?\n";
    else
        cout << "\nWonderful!!!\n\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Functions do not have to return a value in order to be involved with conditional statements. In fact, both issues are fairly independent. This means, void and non-void functions can manipulate values based on conditions internal to the functions. This is illustrated in the following program that is an enhancement to an earlier ergonomic program:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused

//---------------------------------------------------------------------------
#define Or ||
#define And &&
//---------------------------------------------------------------------------
void __fastcall Exit()
{
    cout << "\nPress any key to continue...";
    getch();
}
//---------------------------------------------------------------------------
char __fastcall GetPosition()
{
    char Position;

    do {
        cout << "Are you sitting down now(y/n)? ";
        cin >> Position;

        if( Position != 'y' And
            Position != 'Y' And
            Position != 'n' And
            Position != 'N' )
            cout << "Invalid Answer\n";
    } while( Position != 'y' And
             Position != 'Y' And
             Position != 'n' And
             Position != 'N' );

	return Position;
}
//---------------------------------------------------------------------------
void __fastcall NextExercise()
{
    char LayOnBack;

    cout << "Good. For the next exercise, you should lay on your back";
    cout << "\nAre you laying on your back(1=Yes/0=No)? ";
    cin >> LayOnBack;

    if(LayOnBack == '0')
    {
        char Ready;

        do {
            cout << "Please lay on your back";
            cout << "\nAre you ready(1=Yes/0=No)? ";
            cin >> Ready;
        }while(Ready == '0');
    }
    else if(LayOnBack == '1')
        cout << "\nGreat.\nNow we will start the next exercise.";
    else
        cout << "\nWell, it looks like you are getting tired...";
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    char Position, WantToContinue;

    Position = GetPosition();

    if( Position == 'n' Or Position == 'N' )
        cout << "\nCould you please sit down for the next exercise?";
    else
    {
        cout << "\nWonderful!\nNow we will continue today's exercise...\n";
        cout << "\n...\n\nEnd of exercise\n";
    }

    cout << "\nDo you want to continue(1=Yes/0=No)? ";
    cin >> WantToContinue;

    if( WantToContinue == '1' )
        NextExercise();
    else if( WantToContinue == '0' )
        cout << "\nWell, it looks like you are getting tired...";
    else
    {
        cout << "\nConsidering your invalid answer...";
        cout << "\nWe had enough today";
    }
    cout << "\nWe will stop the session now\nThanks.\n";

    Exit();
    return 0;
}
//---------------------------------------------------------------------------
 

Practical Learning: Conditions in Functions

  1. Create a new console application using the Console Wizard
  2. Save the project in a new folder named Traffic Light5
  3. Save the unit as Main.cpp and save the project as Traffic5
  4. To use conditions in functions, change the program as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    #define OR ||
    #define AND &&
    //---------------------------------------------------------------------------
    enum TDrivingAnswer { daNo, daYes };
    //---------------------------------------------------------------------------
    void __fastcall Exit()
    {
        cout << "\nPress any key to continue...";
        getch();
    }
    //---------------------------------------------------------------------------
    char __fastcall CurrentLight()
    {
        char Light;
    
        // Make sure the user enters a valid letter for a traffic light
        do {
            cout << "What is the current light "
                 << "color(g=Green/y=Yellow/r=Red)? ";
            cin >> Light;
    
            // The user typed an invalid color for the traffic light
            if( Light != 'r' AND Light != 'R' AND
                Light != 'y' AND Light != 'Y' AND
                Light != 'g' AND Light != 'G' )
                cout << "Invalid color\n";
        } while( Light != 'r' AND Light != 'R' AND
                 Light != 'y' AND Light != 'Y' AND
                 Light != 'g' AND Light != 'G' );
    
        return Light;
    }
    //---------------------------------------------------------------------------
    void __fastcall GreenLight()
    {
        cout << "\nThe light is green";
        cout << "\nYou can proceed and drive through.\n";
    }
    //---------------------------------------------------------------------------
    void __fastcall YellowLight()
    {
        int Timer = 0;
    
        while(Timer < 5)
        {
            cout << Timer << ". Yellow Light - Be Careful!\n";
            Timer++;
        }
    
        cout << "\nYellow light ended. Please Stop!!!\n";
    }
    //---------------------------------------------------------------------------
    void __fastcall RedLight()
    {
        int Timer;
    
        cout << "\nShow respect for the red light";
        cout << "\nPlease Stop!!!\n";
    
        for( Timer = 1; Timer < 60; ++Timer)
        {
            if( Timer < 10 )
                cout << " " << Timer << ".Red ";
            else
                cout << Timer << ".Red ";
    
            if( Timer % 10 == 0 )
                cout << endl;
        }
    
        cout << "\n - Red light ended -\n\n";
    }
    //---------------------------------------------------------------------------
    char __fastcall AreYouStillOnTheRoad()
    {
        char Ans;
    
        cout << "\nAre you still on the road(y=Yes/n=No)? ";
        cin >> Ans;
    
        return Ans;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        char Light;
        int Timer;
        char Answer;
    
        do {
            Light = CurrentLight();
    
            // Process a message depending on the current traffic light
            if( Light == 'g' OR Light == 'G' )
                GreenLight();
            else if( Light == 'y' OR Light == 'Y' )
                YellowLight();
            else if( Light == 'r' OR Light == 'R' )
                RedLight();
            else
                cout << endl << Light << " is not a valid color.\n";
    
            Answer = AreYouStillOnTheRoad();
            cout << endl;
        } while((Answer == '1') OR (Answer == 'y') OR (Answer == 'Y') );
    
        cout << "\nNice serving you\n\n";
        Exit();
        return 0;
    }
    //---------------------------------------------------------------------------
  5. Test the program and return to development environment
  6. Save your project
 

Conditional Returns

A function defined other than void must always return a value. Sometimes, a function will perform some tasks whose results would lead to different consequences. A function can return only one value (this is true for this context, but we know that there are ways to pass arguments so that a function can return more than one value) but you can make it render a result depending on a particular behavior. Image that a function is requesting an answer from the user. Since the user can provide different answers, you can treat each result differently.

In the previous section, we saw an example of returning a value from a function. Following our employment application, here is an example of a program that performs a conditional return:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
void __fastcall Exit()
{
    cout << "\nPress any key to continue...";
    getch();
}
//---------------------------------------------------------------------------
bool __fastcall GetAnswer()
{
    char Ans; string Response;

    cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ";
    cin >> Ans;

    if( Ans == 'y' )
        return true;
    else
        return false;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    bool Answer;

    Answer = GetAnswer();

    if( Answer == true )
    {
        cout << "\nThis job involves a high level of self-control.";
        cout << "\nWe will get back to you.\n";
    }
    else
        cout << "\nYou are hired!\n";

    Exit();
    return 0;
}
//---------------------------------------------------------------------------

Imagine you write the following function:

#include <iostream>
#include <conio>
using namespace std;

#define Or ||
#define And &&

string GetPosition()
{
	char Position;
	
	cout << "Are you sitting down now(y/n)? ";
	cin >> Position;
	
	if( Position == 'y' Or Position == 'Y' )
		return "Yes";
	else if( Position == 'n' Or Position == 'N' )
		return "No";
}

int main()
{
	string Answer;
	
	Answer = GetPosition();
	cout << "\nAnswer = " << Answer;
	
	return 0;
}

On paper, the function looks fine. If the user answers with y or Y, the function returns the string Yes. If the user answer with n or N, the function returns the string No. Unfortunately, this function has a problem: what if there is an answer that does not fit those we are expecting? In reality the values that we have returned in the function conform only to the conditional statements and not to the function. Remember that in if(Condidion)Statement;, the Statement executes only if the Condition is true. Here is what will happen. If the user answers y or Y, the function returns Yes and stops; fine, it has returned something, we are happy. If the user answers n or N, the function returns No, which also is a valid value: wonderful. If the user enters another value (other than y, Y, n, or N), the execution of the function will not execute any of the return statements and will not exit. This means that the execution will reach the closing curly bracket without encountering a return value. Therefore, the compiler will issue a warning. Although the warning looks like not a big deal, you should take care of it: never neglect warnings. The solution is to provide a return value so that, if the execution reaches the end of the function, it would still return something. Here is a solution to the problem:

//---------------------------------------------------------------------------
string __fastcall GetPosition()
{
    char Position;

    cout << "Are you sitting down now(y/n)? ";
    cin >> Position;

    if( Position == 'y' Or Position == 'Y' )
        return "Yes";
    else if( Position == 'n' Or Position == 'N' )
        return "No";

    // If you reach here, it means no valid answer was provided.
    // Therefore
    return "Invalid Answer";
}
//---------------------------------------------------------------------------

Here is an example from running the program:

Are you sitting down now(y/n)? w

Answer = Invalid Answer
Press any key to continue...

This is illustrated in the following program that has two functions with conditional returns:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
#define Or ||
#define And &&
//---------------------------------------------------------------------------
void __fastcall Exit()
{
    cout << "\nPress any key to continue...";
    getch();
}
//---------------------------------------------------------------------------
char __fastcall GetPosition()
{
    char Position;

    do {
        cout << "Are you sitting down now(y/n)? ";
        cin >> Position;

        if( Position != 'y' And
            Position != 'Y' And
            Position != 'n' And
            Position != 'N' )
            cout << "Invalid Answer\n";
	} while(Position != 'y' And
            Position != 'Y' And
            Position != 'n' And
            Position != 'N' );

    if( Position == 'y' Or Position == 'Y' )
        return 'y';
    else if( Position == 'n' Or Position == 'N' )
        return 'n';

    // If you reach this point, none of the answers was valid
    return Position;
}
//---------------------------------------------------------------------------
void __fastcall NextExercise()
{
    char LayOnBack;

    cout << "Good. For the next exercise, you should lay on your back";
    cout << "\nAre you laying on your back(1=Yes/0=No)? ";
    cin >> LayOnBack;

    if(LayOnBack == '0')
    {
        char Ready;

        do {
            cout << "Please lay on your back";
            cout << "\nAre you ready(1=Yes/0=No)? ";
            cin >> Ready;
        } while(Ready == '0');
    }
    else if(LayOnBack == '1')
        cout << "\nGreat.\nNow we will start the next exercise.";
    else
        cout << "\nWell, it looks like you are getting tired...";
}
//---------------------------------------------------------------------------
bool __fastcall ValidatePosition(char Pos)
{
    if( Pos == 'y' Or Pos == 'Y' )
        return true;
    else if( Pos == 'n' Or Pos == 'N' )
        return false;

    // If you reached this point, something was not valid
    return false;
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    char Position, WantToContinue;
    bool SittingDown;

    Position = GetPosition();
    SittingDown = ValidatePosition(Position);

    if( SittingDown == false )
        cout << "\nCould you please sit down for the next exercise?";
    else
    {
        cout << "\nWonderful!\nNow we will continue today's exercise...\n";
        cout << "\n...\n\nEnd of exercise\n";
    }

    cout << "\nDo you want to continue(1=Yes/0=No)? ";
    cin >> WantToContinue;

    if( WantToContinue == '1' )
        NextExercise();
    else if( WantToContinue == '0' )
        cout << "\nWell, it looks like you are getting tired...";
    else
    {
        cout << "\nConsidering your invalid answer...";
        cout << "\nWe had enough today";
    }

    cout << "\nWe will stop the session now\nThanks.\n";

    Exit();
    return 0;
}
//---------------------------------------------------------------------------
 

Practical Learning: Functions and Conditional Returns

  1. To implement a function that conditionally returns a value, modify the program as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    //---------------------------------------------------------------------------
    #define OR ||
    #define AND &&
    //---------------------------------------------------------------------------
    enum TDrivingAnswer { daNo, daYes };
    //---------------------------------------------------------------------------
    void __fastcall Exit()
    {
        cout << "\nPress any key to continue...";
        getch();
    }
    //---------------------------------------------------------------------------
    char __fastcall CurrentLight()
    {
        ...
    }
    //---------------------------------------------------------------------------
    void __fastcall GreenLight()
    {
        ...
    }
    //---------------------------------------------------------------------------
    void __fastcall YellowLight()
    {
        ...
    }
    //---------------------------------------------------------------------------
    void __fastcall RedLight()
    {
        ...
    }
    //---------------------------------------------------------------------------
    bool __fastcall AreYouStillOnTheRoad()
    {
        int Ans;
    
        cout << "\nAre you still on the road(0=No/1=Yes)? ";
        cin >> Ans;
    
        if( Ans == 0 )
            return false;
        else if( Ans == 1 )
            return true;
    
        // If you got so far, something went wrong, therefore, return false
        return false;
    }
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        char Light;
        int Timer;
        int Answer;
    
        do {
            Light = CurrentLight();
    
            // Process a message depending on the current traffic light
            if( Light == 'g' || Light == 'G' )
                GreenLight();
            else if( Light == 'y' || Light == 'Y' )
                YellowLight();
            else if( Light == 'r' || Light == 'R' )
                RedLight();
            else
                cout << endl << Light << " is not a valid color.\n";
    
            Answer = AreYouStillOnTheRoad();
            cout << endl;
        } while(Answer == 1);
    
        cout << "\nNice serving you";
        Exit();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Test the program and return to development environment
 
 

Previous Copyright © 2005-2016, FunctionX Next