Lesson Home

Introduction to Functions

 

Function Definition 

 

Introduction

A function is an assignment or a task you are asking the compiler to perform. In order to create and use a function, you must let the compiler know. Letting the compiler know about a function is referred to as declaring it. The syntax of declaring a function is:

ReturnType FunctionName(Needs);

The Return Type of a Function

After a function has performed its assignment, it may produce a result. When a function produces a result, it is also said to return a value. When creating a function, you must specify the type of value that the function will produce or return. For this reason, when declaring a function, start it with the type of value that it will return. A function can return any type of data we have reviewed with variables. If a function will return an integer, you can declare it as short, int, Int16, or Int32, etc. If the function will return a decimal number, you declare it as float, Single, double, Double, or long double. If the function will return a character, you can declare it as char, Char, or __wchar_t. If the function will return a string, you can declare it as string (or String *, as we will learn when studying strings). Based on this, functions can be declared as follows:

int FunctionName(Needs);
Int32 FunctionName(Needs);
double FunctionName(Needs);
string FunctionName(Needs);
Double FunctionName(Needs);

Until we address the issues of Needs of a function, we will ignore these needs for now.

 

The Case of Void Functions

We mentioned above that when a function has performed its assignment, it may return a result. That is how many other languages (such as Pascal or Visual Basic) define a function. In some cases, a function may not return a value (those other languages give it a different name than a function). Because a function must specify whether it returns a value or not, if a function doesn't return a value, it must be declared and defined as void. In Managed C++, the function can also be declared and defined as Void. The Void type is defined in the System namespace. Here are examples of declaring void and Void functions:

void FunctionName();
Void FunctionName();
System::Void FunctionName();

Any function could be a void or Void type as long as you are not expecting it to return a specific value.

 

The Name of a Function

Like everything that is part of a program, a function must have a name. The name of a function follows the same rules we have applied to our variables so far. In addition, a function's name should specify what the function is expected to do. Usually, a verb is appropriate for a function that performs an action. Examples would be add, start, assign, play, etc. A function that validates or sets a condition should have a name like a question. An example would be hasstarted, isvalid.

If the assignment of a function is a combination of words, such as converting a temperature from Celsius to Fahrenheit, you can start the name of the function with a verb and append the necessary words, each starting in uppercase (remember that the name of a function is in one word). Examples include ConvertToFahrenheit, CalculateArea, LoadFromFile, etc. Some functions will not include a verb. They can simply represent a word such as Width, Index, New. They can also be a combination of words; examples include DefaultName, BeforeConstruction, or MethodOfAssignment.

Here are examples of names of functions:

int GetStudentName();
Int32 ValidateGender();
double SynchronizeDistances();
string CreateCompleteAddress();
double CalculateWeeklySalary();
Void Welcome();
System::Void PerformInitialization();

Unlike variables, the declarations of various functions cannot share the same data type. The following declarations will fail:

double SynchronizeDistances(), CalculateWeeklySalary();

This means that each declaration of a function must have its own data type and must end with its own semi-colon. Based on this, the following declarations are valid:

double SynchronizeDistances(); double CalculateWeeklySalary();
   

Function Implementation

Before using a function, it must have been defined. Defining a function is also like describing it. That is, a function definition specifies what the function does. This definition, also called implementation, is done between an opening curly bracket "{" and a closing curly bracket "}". The section between the brackets is also referred to as the body of the function. Therefore, a function's implementation has the following structure:

ReturnType FunctionName() {Body}

As you can see, the name of the function is always followed by parentheses. Its definition is done in the brackets. If the body of the function is short, you can write it in one line. Here are examples:

double CalculateArea() {/*Body*/}
char Answer() {}

If the function is too long, you can use various lines of code. Here is an example:

double CalculateArea() {
/*Body*/
}

Remember that indentation makes code easier to read. The function's body can also appear as follows:

double CalculateArea()
{
    /*Body*/
}

To define a function, start with its return value, followed by the function name, its argument (if any) between parentheses, and the body of the function. Once you have defined a function, other functions can use it.

As an assignment, a function has a body. The body of the function describes what the function is supposed to do. The body starts with an opening curly bracket “{“ and ends with a closing curly bracket “}”. Everything between these two symbols belongs to the function.

In the body of the function, you describe the assignment the function is supposed to perform. As simple as it looks, a function can be used to display a message. Here is an example:

void Message()
{
    Console::Write("This is C++ in its truest form.");
}

A function can also implement a complete behavior. For example, on a program used to perform geometric shape calculations, you can use different functions to handle specific tasks. To create a more and effective program, divide jobs among functions and give each function only the necessary behavior for a specific assignment. A good program is not proven by long and arduous functions.

 

Return Value

The purpose of a function identifies what the function is meant to do. When a function has carried its assignment, it may produce a result. For example, if a function were supposed to calculate the area of a square, the result would be the area of a square. The result of a function used to get a student’s first name would be a word representing a student’s first name. The result of a function is called a return value. A function is also said to return a value.

After a function has finished its assignment, it must indicate the value it returns. To return a value from a function, before closing it, type the return keyword followed by a value or an expression and the traditional semi-colon that ends a statement. For example, suppose you want to create a simple function that returns a number like 12. Before closing the function, you can type return 12;. Such a function can appear as follows:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int GiveMeANumber()
{
    return 120;
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.

    Console::WriteLine();
    return 0;
}

If a function is declared as Boolean, it can return true or false. Here is an example:

Boolean MachineOperating()
{
    return false;
}

If a function is a string type, it can return a string in double-quotes. Here is an example:

string ProvideStudentName()
{
    return "Paul Bertrand Yamaguchi";
}

Function Calling

In order to use a certain function in your program, you must provide its name in the section of code where you want to use it. Providing the name of the function when using it is also referred to as calling a function. When calling such a function, you don't use the declaration formula. This means that you don't specify the return value of the function. You are primarily concerned only with the name of the function, its parentheses, and the contents of those parentheses.

If a function returns a value and if you are using normal C++ code, you can provide the name of the function to a cout extractor. You must also provide the parentheses of the function, leaving them empty. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int GiveMeANumber()
{
    return 120;
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    cout << GiveMeANumber();

    Console::WriteLine();
    return 0;
}

This also means that the GiveMeANumber() function was called. If you are using a function that returns either a normal C++ type or a Managed C++ type, to call that function, you can provide it in the parentheses of Write or WriteLine. Here are examples:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int GiveMeANumber()
{
    return 120;
}

Boolean MachineOperating()
{
    return false;
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Console::Write("Number: ");
    Console::WriteLine(GiveMeANumber());
    Console::Write("Machine Working Status: ");
    Console::WriteLine(MachineOperating());

    Console::WriteLine();
    return 0;
}

As we saw in previous sections, when a function returns a value type, you can box it to display in in Write or WriteLine. To do this, pass the name of the function to the __box operator. Here are examples:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int GiveMeANumber()
{
    return 120;
}

Boolean MachineOperating()
{
    return false;
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Console::WriteLine("Number: {0}", __box(GiveMeANumber()));
    Console::WriteLine("Machine Working Status: {0}", __box(MachineOperating()));

    Console::WriteLine();
    return 0;
}

In C++, before calling a function, the section that calls the function must be aware of that function. Because of this, there are two alternatives of a rule that you must follow. One of the rules you must follow is that a function must be defined before calling it. That's how we have used the GiveMeANumber() function above. The alternate rule is that you can first declare a function without defining it before calling it. To do this, type the return value of the function followed by its name, its parentheses, and a semi-colon. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int GiveMeANumber();

int _tmain()
{
    // TODO: Please replace the sample code below with your own.

    Console::WriteLine();
    return 0;
}

After a function has been declared, it can be called by any other function under it. Then, before the end of the file, you can define the function anywhere. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int GiveMeANumber();

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Console::WriteLine("Number = {0}", __box(GiveMeANumber()));

    Console::WriteLine(S"");
    return 0;
}

int GiveMeANumber()
{
    return 120;
}

If a function was declared as void or Void, it cannot be provided to a cout extractor. Such a function cannot be used in Write or WriteLine either. The following will produce an error:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

System::Void Welcome()
{
    Console::WriteLine("Welcome to Managed C++");
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Console::WriteLine(Welcome());
	
    Console::WriteLine();
    return 0;
}

Therefore, a void or Void function can be called only on its own line. The following will work fine:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

System::Void Welcome()
{
    Console::WriteLine("Welcome to Managed C++");
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Welcome();
	
    Console::WriteLine();
    return 0;
}

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 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 _t main() function that can, in turn, send these results to other functions for further processing. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

#define and &&
#define or  ||

char GetPosition()
{
	char position;

	do {
		Console::Write("Are you sitting down now(y/n)? ");
		cin >> position;

		if(  position != 'y' and position != 'Y' and
			 position != 'n' and position != 'N' )
			Console::WriteLine("\nInvalid Answer");
	} while( position != 'y' and position != 'Y' and
			 position != 'n' and position != 'N' );

	return position;
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char pos;

    pos = GetPosition();
    if( pos == 'n' or pos == 'N' )
        Console::WriteLine("\nCould you please sit down for the next exercise?");
    else
        Console::WriteLine("\nWonderful!!!");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

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

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

Invalid Answer
Are you sitting down now(y/n)? y

Wonderful!!!

Press any key to continue

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 that, 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:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

#define and &&
#define or  ||

char GetPosition()
{
	char position;

	do {
		Console::Write("Are you sitting down now(y/n)? ");
		cin >> position;

		if(  position != 'y' and position != 'Y' and
			 position != 'n' and position != 'N' )
			Console::WriteLine("\nInvalid Answer");
	} while( position != 'y' and position != 'Y' and
			 position != 'n' and position != 'N' );

	return position;
}

void NextExercise()
{
    char layOnBack;

    Console::WriteLine("Good. For the next exercise, you should lay on your back");
    Console::Write("Are you laying on your back(1=Yes/0=No)? ");
    cin >> layOnBack;

    if(layOnBack == '0')
    {
        char ready;

        do {
            Console::WriteLine("\nPlease lay on your back");
            Console::Write("Are you ready(1=Yes/0=No)? ");
            cin >> ready;
        }while(ready == '0');
    }
    else if(layOnBack == '1')
        Console::WriteLine("\nGreat.Now we will start the next exercise.");
    else
        Console::WriteLine("\nWell, it looks like you are getting tired...");
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char pos, wantToContinue;

    pos = GetPosition();

    if( pos == 'n' or pos == 'N' )
        Console::WriteLine("Could you please sit down for the next exercise?");
    else
    {
        Console::WriteLine("Wonderful!Now we will continue today's exercise...");
        Console::WriteLine("...End of exercise");
    }

    Console::Write("Do you want to continue(1=Yes/0=No)? ");
    cin >> wantToContinue;

    if( wantToContinue == '1' )
        NextExercise();
    else if( wantToContinue == '0' )
        Console::WriteLine("Well, it looks like you are getting tired...");
    else
    {
        Console::WriteLine("Considering your invalid answer...");
        Console::WriteLine("We had enough today");
    }
    Console::WriteLine("We will stop the session now\nThanks.");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Are you sitting down now(y/n)? n
Could you please sit down for the next exercise?
Do you want to continue(1=Yes/0=No)? 1
Good. For the next exercise, you should lay on your back
Are you laying on your back(1=Yes/0=No)? 1

Great.Now we will start the next exercise.
We will stop the session now
Thanks.

Press any key to continue
 

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:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

bool GetAnswer()
{
    char answer;

    Console::Write("Do you consider yourself a hot-tempered individual(y=Yes/n=No)? ");
    cin >> answer;

    if( answer == 'y' )
        return true;
    else
        return false;
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    bool ans;

    ans = GetAnswer();

    if( ans == true )
    {
        Console::WriteLine("\nThis job involves a high level of self-control.");
        Console::WriteLine("We will get back to you.");
    }
    else
        Console::WriteLine("You are hired!");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

Do you consider yourself a hot-tempered individual(y=Yes/n=No)? y

This job involves a high level of self-control.
We will get back to you.

Press any key to continue

Imagine you write the following GetPosition() function:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

string GetPosition()
{
	char position;
	
	Console::Write("Are you sitting down now(y/n)? ");
	cin >> position;
	
	if( position == 'y' || position == 'Y' )
		return "Yes";
	else if( position == 'n' || position == 'N' )
		return "No";
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    string ans;
	
    ans = GetPosition();
    cout << "Answer = " << ans;

    Console::WriteLine();
    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 answers 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. If the user answers n or N, the function returns No, which also is a valid value. If the user enters another value (other than y, Y, n, or N), 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. The program may stop and the compiler will display an error:

After clicking NO, you may receive various lines of comments. On this issue, the Managed C++ compiler is not forgiving. Some other compiler would display only a warning. In any case, you should treat this situation as a serious error to eliminate. 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 GetPosition()
{
	char position;
	
	Console::Write("Are you sitting down now(y/n)? ");
	cin >> position;
	
	if( position == 'y' || position == 'Y' )
		return "Yes";
	else if( position == 'n' || 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)? g
Answer = Invalid Answer

Press any key to continue

 

Topics on Implementing Functions

 

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 as inline.

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

inline Int32 GiveMeANumber();

When defining the function, use the inline keyword in the same way. When calling the function, don't use the inline keyword. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

inline Int32 GiveMeANumber();

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Console::WriteLine("Number = {0}", __box(GiveMeANumber()));

    Console::WriteLine();
	return 0;
}

inline Int32 GiveMeANumber()
{
    return 120;
}
 

Functions and Local Variables

In order to carry its assignment, in the body of a function, you can declare variables. Such variables are referred to as local. Here is an example of a locally declared variable:

int GiveMeANumber()
{
    int Number;
    return 120;
}

In the same way, you can declare as many variables as you judge necessary in a function. After declaring a local variable, you can use it as you see fit in the body of the function. For example, you can involve locally declared variables in a calculation and use the result of that calculation as the return value of the function. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int GiveMeANumber()
{
    int Twelve = 12;
    int Ten    = 10;
    int Result = Twelve * Ten;

    return Result;
}

System::Void Welcome()
{
    Console::WriteLine("Welcome to Managed C++");
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    Welcome();
    Console::Write("Number = ");
    Console::WriteLine(GiveMeANumber());
	
    Console::WriteLine();
    return 0;
}

In the same way, if a function returns a value, it can also be assigned to a variable declared locally in another function such as main() or _tmain(). Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int GiveMeANumber()
{
    int Twelve = 12;
    int Ten    = 10;
    int Result = Twelve * Ten;

    return Result;
}

System::Void Welcome()
{
    Console::WriteLine("Welcome to Managed C++");
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int Number;

    Number = GiveMeANumber();

    Welcome();
    Console::Write("Number = ");
    Console::WriteLine(Number);
	
    Console::WriteLine();
    return 0;
}

A function that uses locally declared can also involve them as a returned expression. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int GiveMeANumber()
{
    int Twelve = 12;
    int Ten    = 10;

    return Twelve * Ten;
}

System::Void Welcome()
{
    Console::WriteLine("Welcome to Managed C++");
}

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    int Number;

    Number = GiveMeANumber();
    Welcome();
    Console::Write("Number = ");
    Console::WriteLine(Number);
	
    Console::WriteLine();
    return 0;
}

This would produce:

Welcome to Managed C++
Number = 120

Press any key to continue

If a function were defined as void or Void, it cannot be assigned to a locally declared variable.

 

 

Previous Copyright © 2004-2010 FunctionX, Inc. Next