Home

Introduction to 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;
}

 

 

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