Home

Introduction to Functions

 

Functions

 

Definition

Except when creating a class, all the code we have written so far was confined to main(). This may have made the program simpler but this approach get main() "crowded". As an alternative, instead of performing all your assignments in main(), you can divide the code is smaller or relatively smaller sections of code so that each section is meant to perform a specify task. Other sections of the program can then refer to that section for whatever it has to provide. Such a section of code is called a function.

Fundamentals of Creating a Function

To create a function, there are some rules you must follow. The fundamental formula is:

ReturnType FunctionName() { }

The first rule is that the function must be created outside of any other function. This means that you cannot create a function inside of main().

The ReturnType is the kind of value that the function will produce. Some functions don't produce a (specific) result. In this case, the ReturnType can be substituted with the void keyword.

Like a variable, a function must have a name. The name follows the rules we have applied to variables so far. Because a function usually performs an action or a task, its name should reflect a verb. Examples of function names are Show or Display. In some cases, the name will be made of more than one word. You should still make sure that the name reflects an assignment.

The name of a function must be followed by parentheses.

The parentheses of a function must be followed by an opening curly bracket "{" and a closing curly bracket "}". The section inside of the curly brackets is referred to as the body of the function. In this body, you perform the assignment of the function. For example, a function can be used to simply display a sentence. Here is an example:

void Introduction() { Console::WriteLine(L"The Wonderful World of C++/CLI"); }

Writing a function like this, with its name and body, is referred to as defining or implementing it.

This appears as a simple assignment. In most cases, a function will be more complex than that. In fact, the body of a function can become quite crowded. For this reason, you should spread its body on different lines. In this case, at least the closing curly bracket should stand on its own line and as the last. Where you place the opening curly bracket, whether on the same line as the name of the function or on its own line is a matter of choice. Based on this, here another way to write the above function:

using namespace System;

void Introduction()
{
	Console::WriteLine(L"The Wonderful World of C++/CLI");
}

int main()
{
	return 0;
}

In the same way, you can define or implement as many functions as you judge necessary.

Calling a Function

After creating a function, you can use it either inside of itself or from another function. Using a function is referred to as calling it. To call a function, type its name, followed by parentheses. If the function is called as a statement, then it must be terminated with a semi-colon. Here is an example:

using namespace System;

void Introduction()
{
	Console::WriteLine(L"The Wonderful World of C++/CLI");
}

int main()
{
	Introduction();

	return 0;
}

This would produce:

The Wonderful World of C++/CLI
Press any key to continue . . .

In the above examples, we defined the function before calling it. As an alternative, you can first declare a function and define it somewhere in your program. The main rule to observe in this case it that you must make sure the compiler can find the definition of the function when calling it. You can declare (but not define) a function inside of another function, then define the function outside. Here is an example:

using namespace System;

int main()
{
	void IdentifyHouse();

	Console::WriteLine();

	return 0;
}

void IdentifyHouse()
{
	__wchar_t TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = __wchar_t::Parse(Console::ReadLine());

	Console::WriteLine(L"\nType of Home: {0}", TypeOfHome);
}

Once the function has been declared, you can call it even if it is defined later in the source file. Here is an example that calls the above function:

using namespace System;

int main()
{
	void IdentifyHouse();

	IdentifyHouse();
	Console::WriteLine();

	return 0;
}

void IdentifyHouse()
{
	__wchar_t TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = __wchar_t::Parse(Console::ReadLine());

	Console::WriteLine(L"\nType of Home: {0}", TypeOfHome);
}

If you declare a function A inside of another B, that declared function A can be accessed only inside of the second function B. If you want other functions to be able to access a function, you can either define it above all functions that would call it, or declare it globally, that is, above and outside of any function. Here is an example:

using namespace System;

void IdentifyHouse();

int main()
{
	IdentifyHouse();

	Console::WriteLine();

	return 0;
}

void IdentifyHouse()
{
	__wchar_t TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = __wchar_t::Parse(Console::ReadLine());

	Console::WriteLine(L"\nType of Home: {0}", TypeOfHome);
}

Practical LearningPractical Learning: Introducing Functions

  1. To start a new program, launch Microsoft Visual C++ 2005
  2. On the main menu, click File -> New -> Project...
  3. On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
  4. In the Name box, replace the string with RealEstate9 and click OK
  5. To create a source file, on the main menu, click Project -> Add New Item...
  6. In the Templates list, click Source File (.cpp)
  7. In the New box, type Exercise and click Add
  8. In the empty file, type:
     
    #include <iostream>
    
    using namespace std;
    using namespace System;
    
    void CreateAndShowProperty()
    {
        long propertyNumber;
        int condition;
        Byte stories;
        unsigned int bedrooms;
        float bathrooms;
        unsigned int yearBuilt;
        __wchar_t style;
        double marketValue;
    
        String ^ strTitle1 = L"=//= Altair Realty =//=";
        String ^ strTitle2 = L"-=- Properties Inventory -=-";
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("To create a listing, enter the following information");
        Console::Write("Property #:    ");
        propertyNumber = long::Parse(Console::ReadLine());
        Console::WriteLine("Property Condition");
        Console::WriteLine("0. Unknown");
        Console::WriteLine("1. Excellent");
        Console::WriteLine("2. Good (may need minor repair");
        Console::WriteLine("3. Acceptable (needs major repair)");
        Console::WriteLine("4. Even (land is more important)");
        Console::Write("Your Choice:    ");
        condition = int::Parse(Console::ReadLine());
        Console::Write("Bedrooms:       ");
        bedrooms = int::Parse(Console::ReadLine());
        Console::Write("Bathrooms:      ");
        bathrooms = float::Parse(Console::ReadLine());
        Console::Write("Stories:        ");
        stories = int::Parse(Console::ReadLine());
        Console::Write("Year Built:     ");
        yearBuilt = int::Parse(Console::ReadLine());
        Console::WriteLine("Style");
        Console::WriteLine("U. Unknown");
        Console::WriteLine("S. Split Level");
        Console::WriteLine("C. Colonial");
        Console::WriteLine("G. Georgial");
        Console::Write("Your Choice:    ");
        style = __wchar_t::Parse(Console::ReadLine());
        Console::Write("Market Value:   ");
        marketValue = double::Parse(Console::ReadLine());
      
        system("cls");
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("=//= Property Listing =//=");
        Console::WriteLine("Property #:    {0}", propertyNumber);
        Console::WriteLine("Condition:     {0}", condition);
        Console::WriteLine("Style:         {0}", style);
        Console::WriteLine("Bedrooms:      {0}", bedrooms);
        Console::WriteLine("Bathrooms:     {0}", bathrooms);
        Console::WriteLine("Stories:       {0}", stories);
        Console::WriteLine("Year Built:    {0}", yearBuilt);
        Console::WriteLine("Market Value:  {0:C}", marketValue);
    }
    
    int main()
    {
        CreateAndShowProperty();
    
        Console::WriteLine();
        return 0;
    }
  9. To execute the application, on the main menu, click Debug -> Start Without Debugging
     

    Screen 1

    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    To create a listing, enter the following information
    Property #:    698624
    Property Condition
    0. Unknown
    1. Excellent
    2. Good (may need minor repair
    3. Acceptable (needs major repair)
    4. Even (land is more important)
    Your Choice:    2
    Bedrooms:       3
    Bathrooms:      1.5
    Stories:        3
    Year Built:     1994
    Style
    U. Unknown
    S. Split Level
    C. Colonial
    G. Georgial
    Your Choice:    S
    Market Value:   420880
    Screen 2
    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    =//= Property Listing =//=
    Property #:    698624
    Condition:     2
    Style:         S
    Bedrooms:      3
    Bathrooms:     1.5
    Stories:       3
    Year Built:    1994
    Market Value:  $420,880.00
    
    Press any key to continue . . .
  10. Close the DOS window

Inline Functions

When you call a function B() from function A(), function A() sends a request and must get to Function B(). 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 void IdentifyHouse()

When defining the function, use the inline keyword in the same way. You can place the inline keyword before or after the return type or void. Here is an example that makes use of an inline function:

using namespace System;

void inline IdentifyHouse()
{
	__wchar_t TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = __wchar_t::Parse(Console::ReadLine());

	Console::WriteLine(L"\nType of Home: {0}", TypeOfHome);
}

int main()
{
	IdentifyHouse();

	Console::WriteLine();

	return 0;
}

Techniques of Returning a Value

 

Returning a Primitive Type

The main purpose of using a function in a program is to perform an assignment. In some cases, you may want that function to produce a result. When declaring or defining a function, you must clearly indicate this to the compiler. Therefore, the function is said to return a value. To indicate that a function must return a value, precede its name with the type of value that it would return. This means that, depending on your intentions, one function can be made to produce a number, another function can be defined to return a character, yet another function could produce a Boolean value. Here is an example of a function that will return a character:

__wchar_t IdentifyHouse()
{
}

In the body of the function, you can perform any type of assignment that is necessary. The most important rule is that, before the function is closed, that it, before the closing curly bracket, the function must have returned a value of the appropriate type. To return a value from a function, type the return keyword, followed by the value being returned, followed by a semi-colon. Here is an example:

__wchar_t IdentifyHouse()
{
	return L'S';
}

You can also declare a local variable, process it, and return it from a function. Here is an example:

using namespace System;

__wchar_t GetHouseType();

int main()
{
	Console::WriteLine(L"\nType of Home: {0}", GetHouseType());

	Console::WriteLine();

	return 0;
}

__wchar_t GetHouseType()
{
	__wchar_t type;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	type = __wchar_t::Parse(Console::ReadLine());

	return type;
}

Practical LearningPractical Learning: Returning a Primitive Type

  1. To create functions that return some values, change the file as follows:
     
    #include <iostream>
    
    using namespace std;
    using namespace System;
    
    long GetPropertyNumber()
    {
        long propertyNumber;
    
        Console::Write("Property #:    ");
        propertyNumber = long::Parse(Console::ReadLine());
        return propertyNumber;
    }
    
    int GetPropertyCondition()
    {
        int condition;
    
        Console::WriteLine("Property Condition");
        Console::WriteLine("0. Unknown");
        Console::WriteLine("1. Excellent");
        Console::WriteLine("2. Good (may need minor repair");
        Console::WriteLine("3. Acceptable (needs major repair)");
        Console::WriteLine("4. Even (land is more important)");
        Console::Write("Your Choice:    ");
        condition = int::Parse(Console::ReadLine());
        return condition;
    }
    
    Byte GetNumberOfStories()
    {
        Byte stories;
    
        Console::Write("Stories:        ");
        stories = int::Parse(Console::ReadLine());
        return stories;
    }
    
    unsigned int GetBedrooms()
    {
        unsigned int bedrooms;
    
        Console::Write("Bedrooms:       ");
        bedrooms = int::Parse(Console::ReadLine());
        return bedrooms;
    }
    
    __wchar_t GetPropertyStype()
    {
        __wchar_t style;
    
        Console::WriteLine("Style");
        Console::WriteLine("U. Unknown");
        Console::WriteLine("S. Split Level");
        Console::WriteLine("C. Colonial");
        Console::WriteLine("G. Georgial");
        Console::Write("Your Choice:    ");
        style = __wchar_t::Parse(Console::ReadLine());
        return style;
    }
    
    double GetPropertyValue()
    {
        double marketValue;
    
        Console::Write("Market Value:   ");
        marketValue = double::Parse(Console::ReadLine());
        return marketValue;
    }
    
    float GetBathrooms()
    {
        float bathrooms;
    
        Console::Write("Bathrooms:      ");
        bathrooms = float::Parse(Console::ReadLine());
    	return bathrooms;
    }
    
    unsigned int GetYearBuilt()
    {
        unsigned int yearBuilt;
    
        Console::Write("Year Built:     ");
        yearBuilt = int::Parse(Console::ReadLine());
        return yearBuilt;
    }
    
    void CreateAndShowProperty()
    {
        long propertyNumber;
        int condition;
        Byte stories;
        unsigned int bedrooms;
        float bathrooms;
        unsigned int yearBuilt;
        __wchar_t style;
        double marketValue;
    
        String ^ strTitle1 = L"=//= Altair Realty =//=";
        String ^ strTitle2 = L"-=- Properties Inventory -=-";
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("To create a listing, enter the following information");
    
        propertyNumber = GetPropertyNumber();
        condition      = GetPropertyCondition();
        stories        = GetNumberOfStories();
        bedrooms       = GetBedrooms();
        bathrooms      = GetBathrooms();
        yearBuilt      = GetYearBuilt();
        style          = GetPropertyStype();
        marketValue    = GetPropertyValue();
    
        system("cls");
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("=//= Property Listing =//=");
        Console::WriteLine("Property #:    {0}", propertyNumber);
        Console::WriteLine("Condition:     {0}", condition);
        Console::WriteLine("Style:         {0}", style);
        Console::WriteLine("Bedrooms:      {0}", bedrooms);
        Console::WriteLine("Bathrooms:     {0}", bathrooms);
        Console::WriteLine("Stories:       {0}", stories);
        Console::WriteLine("Year Built:    {0}", yearBuilt);
        Console::WriteLine("Market Value:  {0:C}", marketValue);
    }
    
    int main()
    {
        CreateAndShowProperty();
    
        Console::WriteLine();
        return 0;
    }
  2. Execute the application to test it 
  3. Close the DOS window

Returning a Native Reference

As a function can be created to return a value of a primitive type, a function can also be defined to return a reference to a primitive type. When declaring such a function, you must indicate that it is returning a reference by preceding it with the & operator. Here is an example:

double & GetPropertyValue()
{
    double Value = 406500.00;
    double &rValue = Value;
    return rValue;
}

In the body of the function, define the desired behavior as you see fit. The most important rule to apply is that the function must return not only a reference but a reference to the appropriate type. When returning the value, don't precede the name of the variable with &. Here is an example:

double & GetPropertyValue()
{
    double Value = 406500.00;
    double &rValue = Value;
    return rValue;
}

When calling a function that returns a reference, you can proceed as if it returns a regular value but of the appropriate type. Here is an example:

using namespace System;
 
double & GetPropertyValue()
{
    double Value = 406500.00;
    double &rValue = Value;
    return rValue;
}

int main()
{
	double PropertyValue = GetPropertyValue();

	Console::WriteLine(L"Property Value: ${0}\n", PropertyValue);

	return 0;
}

This would produce:

Property Value: $406500

Press any key to continue . . .
 

Returning a Tracking Reference

Just as you can return a reference to a primitive type, you can also return a tracking reference either to a primitive type or to a class. To declare a function that returns a tracking reference, type the % operator between its return type and its name. In the body of the function, you can create the behavior you want. Before the close curly bracket of the function, you must have returned a tracking reference of the indicated type.

When calling a function that returns a tracking reference, proceed as you would for a native reference. Here is an example:

using namespace System;
 
Byte % GetStories()
{
    Byte lvl;

    Console::Write(L"How many levels does the house have? ");
    lvl = Byte::Parse(Console::ReadLine());

    Byte % Levels = lvl;
    return Levels;
}

int main()
{
    Byte Stories = GetStories();

    Console::WriteLine(L"Number of Stories: {0}\n", Stories);

    return 0;
}

Here is an example of running the program:

How many levels does the house have? 4
Number of Stories: 4

Press any key to continue . . .

Returning a Pointer

Instead of a regular value or even a reference, a function can return a pointer. You can start to specify this by typing the * operator on the left side of the function's name. Here is an example:

double * GetBathrooms()
{
}

Use the body of the function to define it. Before the closing curly bracket of the function, remember to return a pointer to the return value. Here is an example:

double * GetBathrooms()
{
    double rooms = 0;

    Console::Write(L"How many bathrooms in the house? ");
    rooms = double::Parse(Console::ReadLine());
    double *Bathrooms = &rooms;

    return Bathrooms;
}

After defining the function, you can call it. Remember that the asterisk is used to get the value of a pointer. This means that, when calling the function, if you want to access its value, make sure you include the asterisk on the left side of the name of the function. Here is an example:

using namespace System;
 
double * GetBathrooms()
{
    double rooms = 0;

    Console::Write(L"How many bathrooms in the house? ");
    rooms = double::Parse(Console::ReadLine());
    double *Bathrooms = &rooms;

    return Bathrooms;
}

int main()
{
    double bRooms = *GetBathrooms();

    Console::WriteLine(L"Number of Bathrooms: {0:F}\n", bRooms);

    return 0;
}

This would produce:

How many bathrooms in the house? 2.5
Number of Bathrooms: 2.50

Press any key to continue . . .

Returning a Handle

If you want to process a function in the managed heap, you can make it return a handle. When declaring or defining the function, precede it with a handle type. When you finish using the function, make sure it returns a value that is a handle. The rules are the same for pointers.

Practical LearningPractical Learning: Returning a Handle

  1. To show different ways of returning a handle, change the file as follows:
    #include <iostream>
    
    using namespace std;
    using namespace System;
    
    long ^ GetPropertyNumber()
    {
        long ^ propertyNumber = gcnew long;
    
        Console::Write("Property #:    ");
        propertyNumber = long::Parse(Console::ReadLine());
        return propertyNumber;
    }
    
    int ^ GetPropertyCondition()
    {
        Console::WriteLine("Property Condition");
        Console::WriteLine("0. Unknown");
        Console::WriteLine("1. Excellent");
        Console::WriteLine("2. Good (may need minor repair");
        Console::WriteLine("3. Acceptable (needs major repair)");
        Console::WriteLine("4. Even (land is more important)");
        Console::Write("Your Choice:    ");
        int ^ condition = int::Parse(Console::ReadLine());
        return condition;
    }
    
    Byte ^ GetNumberOfStories()
    {
        Byte ^ stories = gcnew Byte;
    
        Console::Write("Stories:        ");
        *stories = int::Parse(Console::ReadLine());
        return stories;
    }
    
    unsigned int ^ GetBedrooms()
    {
        unsigned int ^ bedrooms = gcnew unsigned int;
    
        Console::Write("Bedrooms:       ");
        bedrooms = UInt32::Parse(Console::ReadLine());
        return bedrooms;
    }
    
    __wchar_t GetPropertyStype()
    {
        __wchar_t style;
    
        Console::WriteLine("Style");
        Console::WriteLine("U. Unknown");
        Console::WriteLine("S. Split Level");
        Console::WriteLine("C. Colonial");
        Console::WriteLine("G. Georgial");
        Console::Write("Your Choice:    ");
        style = __wchar_t::Parse(Console::ReadLine());
        return style;
    }
    
    double GetPropertyValue()
    {
        double marketValue;
    
        Console::Write("Market Value:   ");
        marketValue = double::Parse(Console::ReadLine());
        return marketValue;
    }
    
    float GetBathrooms()
    {
        float bathrooms;
    
        Console::Write("Bathrooms:      ");
        bathrooms = float::Parse(Console::ReadLine());
    	return bathrooms;
    }
    
    unsigned int GetYearBuilt()
    {
        unsigned int yearBuilt;
    
        Console::Write("Year Built:     ");
        yearBuilt = int::Parse(Console::ReadLine());
        return yearBuilt;
    }
    
    void CreateAndShowProperty()
    {
        long^ propertyNumber = gcnew long;
        int ^ condition = gcnew int;
        Byte ^stories = gcnew Byte;
        unsigned int ^ bedrooms = gcnew unsigned int;
        float bathrooms;
        unsigned int yearBuilt;
        __wchar_t style;
        double marketValue;
    
        String ^ strTitle1 = L"=//= Altair Realty =//=";
        String ^ strTitle2 = L"-=- Properties Inventory -=-";
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("To create a listing, enter the following information");
    
        propertyNumber = GetPropertyNumber();
        condition      = GetPropertyCondition();
        stories        = GetNumberOfStories();
        bedrooms       = GetBedrooms();
        bathrooms      = GetBathrooms();
        yearBuilt      = GetYearBuilt();
        style          = GetPropertyStype();
        marketValue    = GetPropertyValue();
    
        system("cls");
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("=//= Property Listing =//=");
        Console::WriteLine("Property #:    {0}", propertyNumber);
        Console::WriteLine("Condition:     {0}", condition);
        Console::WriteLine("Style:         {0}", style);
        Console::WriteLine("Bedrooms:      {0}", bedrooms);
        Console::WriteLine("Bathrooms:     {0}", bathrooms);
        Console::WriteLine("Stories:       {0}", stories);
        Console::WriteLine("Year Built:    {0}", yearBuilt);
        Console::WriteLine("Market Value:  {0:C}", marketValue);
    }
    
    int main()
    {
        CreateAndShowProperty();
    
        Console::WriteLine();
        return 0;
    }
  2. Execute the application to test it  
  3. Close the DOS window

Introduction to Functions Parameters

 

Overview of Parameters

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:

Tax Amount

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

Final Price = Item Price + Tax Amount

Here is an example:

using namespace System;
 
double RequestOriginalPrice()
{
    double Price;

    Console::Write("Enter the original price: $");
    Price = double::Parse(Console::ReadLine());
    return Price;
}

double RequestDiscountRate()
{
    double Discount;

    Console::Write("Enter discount rate(0.00 to 100.00): ");
    Discount = double::Parse(Console::ReadLine());
    return Discount;
}

double RequestTaxRate()
{
    double Tax;

    Console::Write("Enter the tax rate(0.00 to 100.00): ");
    Tax = double::Parse(Console::ReadLine());
    return Tax;
}

int main()
{
    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;

    Console::WriteLine("\nReceipt");
    Console::WriteLine("Original Price:  {0:C}", OriginalPrice);
    Console::WriteLine("Discount Rate:   {0}%", DiscountRate);
    Console::WriteLine("Discount Amount: {0:C}", DiscountAmount);
    Console::WriteLine("After Discount:  {0:C}", PriceAfterDiscount);
    Console::WriteLine("Tax Rate:        {0}%", TaxRate);
    Console::WriteLine("Tax Amount:      {0:C}", TaxAmount);
    Console::WriteLine("Net Price:       {0:C}", NetPrice);

    return 0;
}

Here is an example of running the program:

Enter the original price: $450
Enter discount rate(0.00 to 100.00): 70
Enter the tax rate(0.00 to 100.00): 5.75

Receipt
Original Price:  $450.00
Discount Rate:   70%
Discount Amount: $315.00
After Discount:  $135.00
Tax Rate:        5.75%
Tax Amount:      $7.76
Net Price:       $142.76
Press any key to continue . . .

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(__wchar_t 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.

When a function receives an argument, it can ignore that argument. Here is an example:

void Multiply(double Value)
{
	Console::WriteLine(L"Multiplication");
}

To call a function that takes an argument, specify the name of the function and its list of arguments (if any) inside of parentheses. You can pass the constant value of an argument. Here is an example:

using namespace System;

void Multiply(double Value)
{
	Console::WriteLine(L"Multiplication");
}

int main()
{
	Multiply(25.75);

	return 0;
}

This would produce:

Multiplication
Press any key to continue . . .

When calling the function, if the value is stored in a variable, you can pass the name of the variable in place of the argument. Here is an example:

using namespace System;

void Multiply(double Value)
{
	Console::WriteLine(L"Multiplication");
}

int main()
{
	double HourlySalary = 25.75;

	Multiply(HourlySalary);

	return 0;
}

When defining a function that takes a parameter, in the body of the function, you can use the argument appropriately as you see fit. One the minimum operations you can perform is to involve the argument in an expression. Here is an example:

using namespace System;

void Multiply(double Value)
{
	double Weekly;

	Weekly = Value * 36.50;
	Console::WriteLine(L"Hourly Salary: ${0}", Value);
	Console::WriteLine(L"Weekly Salary: ${0}", Weekly);
}

int main()
{
	double HourlySalary = 25.75;

	Multiply(HourlySalary);

	return 0;
}

This would produce:

Hourly Salary: $25.75
Weekly Salary: $939.875
Press any key to continue . . .

You can also define a function that returns the value of the argument. Here is an example:

double Multiply(double Value)
{
	return Value;
}

Remember that, depending on the goals you set for your function, you can use as many parameters as you want. Here is example:

void CalculateRateAmount(double price, double rate)
{
}

As seen in previous sections, 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 constant value or a complete expression. 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 don't 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. Here is example:

double CalculateRateAmount(double price, double rate)
{
    return price * rate / 100;
}

To call a function that takes more than one parameter, provide a value for each parameter in the parentheses of the function, in the order the parameters are listed in the function.

When declaring a function, the compiler doesn't 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 provided by the presence of a data type. This means you can declare a function with only the data type of an argument. Here is an example:

double CalculateRateAmount(double, double);

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

The compiler also doesn't 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.

Practical LearningPractical Learning: Introducing Functions

  1. To see an example of passing arguments to a function, change the file as follows:
    #include <iostream>
    
    using namespace std;
    using namespace System;
    
    void ShowAppTitle();
    void CreateProperty();
    void ShowProperty(long propNbr, int cond, Byte levels,
    		  unsigned int beds, float baths,
    		  unsigned int year, __wchar_t style, double value);
    
    long GetPropertyNumber()
    {
        long propertyNumber;
    
        Console::Write("Property #:    ");
        propertyNumber = long::Parse(Console::ReadLine());
        return propertyNumber;
    }
    
    int GetPropertyCondition()
    {
        Console::WriteLine("Property Condition");
        Console::WriteLine("0. Unknown");
        Console::WriteLine("1. Excellent");
        Console::WriteLine("2. Good (may need minor repair");
        Console::WriteLine("3. Acceptable (needs major repair)");
        Console::WriteLine("4. Even (land is more important)");
        Console::Write("Your Choice:    ");
        int condition = int::Parse(Console::ReadLine());
        return condition;
    }
    
    Byte GetNumberOfStories()
    {
        Byte stories;
    
        Console::Write("Stories:        ");
        stories = int::Parse(Console::ReadLine());
        return stories;
    }
    
    unsigned int GetBedrooms()
    {
        unsigned int bedrooms;
    
        Console::Write("Bedrooms:       ");
        bedrooms = int::Parse(Console::ReadLine());
        return bedrooms;
    }
    
    __wchar_t GetPropertyStype()
    {
        __wchar_t style;
    
        Console::WriteLine("Style");
        Console::WriteLine("U. Unknown");
        Console::WriteLine("S. Split Level");
        Console::WriteLine("C. Colonial");
        Console::WriteLine("G. Georgial");
        Console::Write("Your Choice:    ");
        style = __wchar_t::Parse(Console::ReadLine());
        return style;
    }
    
    double GetPropertyValue()
    {
        double marketValue;
    
        Console::Write("Market Value:   ");
        marketValue = double::Parse(Console::ReadLine());
        return marketValue;
    }
    
    float GetBathrooms()
    {
        float bathrooms;
    
        Console::Write("Bathrooms:      ");
        bathrooms = float::Parse(Console::ReadLine());
        return bathrooms;
    }
    
    unsigned int GetYearBuilt()
    {
        unsigned int yearBuilt;
    
        Console::Write("Year Built:     ");
        yearBuilt = int::Parse(Console::ReadLine());
        return yearBuilt;
    }
    
    int main()
    {
        Console::WriteLine("To create a listing, enter the following information");
    
        CreateProperty();
    
        Console::WriteLine();
        return 0;
    }
    
    void ShowAppTitle()
    {
        String ^ strTitle1 = L"=//= Altair Realty =//=";
        String ^ strTitle2 = L"-=- Properties Inventory -=-";
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
    }
    
    void CreateProperty()
    {
        long propertyNumber;
        int  condition;
        Byte stories;
        unsigned int bedrooms;
        float bathrooms;
        unsigned int yearBuilt;
        __wchar_t style;
        double marketValue;
    
        ShowAppTitle();
        Console::WriteLine("To create a listing, enter the following information");
    
        propertyNumber = GetPropertyNumber();
        condition      = GetPropertyCondition();
        stories        = GetNumberOfStories();
        bedrooms       = GetBedrooms();
        bathrooms      = GetBathrooms();
        yearBuilt      = GetYearBuilt();
        style          = GetPropertyStype();
        marketValue    = GetPropertyValue();
    	
        system("cls");
    
        ShowAppTitle();
        ShowProperty(propertyNumber, condition, stories,
    				 bedrooms, bathrooms, yearBuilt,
    				 style, marketValue);
    }
    
    void ShowProperty(long propNbr, int cond, Byte levels,
    	          unsigned int beds, float baths,
    		  unsigned int year, __wchar_t style, double value)
    {
        Console::WriteLine("=//= Property Listing =//=");
        Console::WriteLine("Property #:    {0}", propNbr);
        Console::WriteLine("Condition:     {0}", cond);
        Console::WriteLine("Style:         {0}", style);
        Console::WriteLine("Bedrooms:      {0}", beds);
        Console::WriteLine("Bathrooms:     {0}", baths);
        Console::WriteLine("Stories:       {0}", levels);
        Console::WriteLine("Year Built:    {0}", year);
        Console::WriteLine("Market Value:  {0:C}", value);
    }
    
  2. Execute the application and test it. Here is an example:
     

    Screen 1

    To create a listing, enter the following information
    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    To create a listing, enter the following information
    Property #:    834845
    Property Condition
    0. Unknown
    1. Excellent
    2. Good (may need minor repair
    3. Acceptable (needs major repair)
    4. Even (land is more important)
    Your Choice:    0
    Stories:        3
    Bedrooms:       3
    Bathrooms:      2.5
    Year Built:     1996
    Style
    U. Unknown
    S. Split Level
    C. Colonial
    G. Georgial
    Your Choice:    C
    Market Value:   585425
    Screen 2
    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    =//= Property Listing =//=
    Property #:    834845
    Condition:     0
    Style:         C
    Bedrooms:      3
    Bathrooms:     2.5
    Stories:       3
    Year Built:    1996
    Market Value:  $585,425.00
    
    Press any key to continue . . .
  3. Close the DOS window

Static Variables

Consider the following program:

using namespace System;

void Starter(int y)
{
    double a = 112.50;
    double b = 175.25;

    a = a / y;
    b = b + 2;

    Console::WriteLine("y     = {0}", y);
    Console::WriteLine("a     = {0}", a);
    Console::WriteLine("b     = {0}", b);
    Console::WriteLine("b / a = {0}\n", b / a);
}

int main()
{
    Starter(2);
    Starter(2);
    Starter(2);
    Starter(2);

    return 0;
}

This program would produce:

y     = 2
a     = 56.25
b     = 177.25
b / a = 3.15111111111111

y     = 2
a     = 56.25
b     = 177.25
b / a = 3.15111111111111

y     = 2
a     = 56.25
b     = 177.25
b / a = 3.15111111111111

y     = 2
a     = 56.25
b     = 177.25
b / a = 3.15111111111111

Press any key to 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:

using namespace System;

void Starter(int y)
{
    static double a = 112.50;
    static double b = 175.25;

    a = a / y;
    b = b + 2;

    Console::WriteLine("y     = {0}", y);
    Console::WriteLine("a     = {0}", a);
    Console::WriteLine("b     = {0}", b);
    Console::WriteLine("b / a = {0}\n", b / a);
}

int main()
{
    Starter(2);
    Starter(2);
    Starter(2);
    Starter(2);
    
    return 0;
}

This time, when executing the program, it would produce:

y     = 2
a     = 56.25
b     = 177.25
b / a = 3.15111111111111

y     = 2
a     = 28.125
b     = 179.25
b / a = 6.37333333333333

y     = 2
a     = 14.0625
b     = 181.25
b / a = 12.8888888888889

y     = 2
a     = 7.03125
b     = 183.25
b / a = 26.0622222222222

Press any key to 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:

using namespace System;

void Starter(int y)
{
    static double a = 112.50;
    static double b = 175.25;

    a = a / y;
    b = b + 2;

    Console::WriteLine("y     = {0}", y);
    Console::WriteLine("a     = {0}", a);
    Console::WriteLine("b     = {0}", b);
    Console::WriteLine("b / a = {0}\n", b / a);
}

int main()
{
    Starter(2);
    Starter(5);
    Starter(14);
    Starter(25);

    Console::WriteLine();
    
    return 0;
}

The current version of the program would produce:

y     = 2
a     = 56.25
b     = 177.25
b / a = 3.15111111111111

y     = 5
a     = 11.25
b     = 179.25
b / a = 15.9333333333333

y     = 14
a     = 0.803571428571429
b     = 181.25
b / a = 225.555555555556

y     = 25
a     = 0.0321428571428571
b     = 183.25
b / a = 5701.11111111111


Press any key to continue . . .

Previous Copyright © 2006-2016, FunctionX, Inc. Next