CREATING FUNCTIONS


The previous chapter's project, the Dice Poker game, required you to create three custom functions: RollTheDice, Total TheScore, and EndOfGame. The purpose of these functions was to cut down on the overall detail of the project, make the code more readable, and allow you to execute certain blocks of code continuously without duplicating large blocks of code or using unnaturally large loops. The result was that the overall development of the game was simplified. As your applications continue to grow in both size and complexity, you will come to rely on functions for the detail reduction, flexibility, and improvements to readability that they provide.

Hint 

A function is a collection of program statements that is called and executed as a unit. When associated with objects, functions are called methods.

At their core, functions make an application easier to develop by allowing you to break it down into smaller pieces. These smaller pieces are then, in code, fitted together to perform all your application's tasks. When you create a function, you gain the ability to logically group related statements and to focus on writing your application one function at a time.

Because you can call and execute a function over and over again as needed, functions also enable you to reduce the overall amount of code that you must write. This, in turn, makes your application easier to create and easier to maintain over time. If your application's major functionality is isolated into functions, for example, it is easier to change its features without impacting the rest of the code.

When you find yourself adding code to perform a major operation within the application, particularly one that is executed often, you usually have a good candidate for a function. For example, if you have several locations where you need to perform the same steps to validate user input, enclosing the code in a function allows you to invoke its functionality simply by using the function's name.

The syntax for a function is as follows:

 [Return Type] Function Name([Arguments]); 

To use a function, you must know three things:

  • Its name

  • What, if any, data you must give it (placed in parentheses after its name)

  • What, if any, data the function returns as a result of its operations

image from book
IN THE REAL WORLD

Professional programmers often try to limit each function they write to performing one single, major operation or task that the application requires. This makes application code more modular and streamlined. It also helps to isolate errors.

When it comes to fixing bugs, functions can be likened to fire doors on a ship or within a building. They isolate problems within a given section of the code. You can locate bugs within a function more easily when program flow executes to specific, reliable points. Functions are those points. If, for example, a programmer adds 100 new lines of code to an application he is working on and suddenly discovers that the program no longer behaves properly, he might have a hard time figuring out where the problem lies. However, if this code is contained within four or five functions, the programmer stands a better chance of locating the bug more quickly because he can comment out functions one by one to determine where the error lies.

image from book

In same cases, the latter two points might be optional, because a function cannot accept or return data.

Don't worry yet about understanding the specific elements of a function. I'll cover them in the next sections. First, try to concentrate on the big picture of what a function is.

Calling a Function

When you use a function's name in your code, you are said to be calling that function, or making a function call. Doing so causes Visual C++ to execute the code related to the name, which you define somewhere within your program or in another file. For example, if you wanted to use a function called ValidateInput, which ensures that a user has made the proper input, you would write its name on a line by itself, followed by the data to send to the function, followed by a semicolon:

 ValidateInput(); 

In the previous chapter's game, Dice Poker, when you wrote RollTheDice, Total TheScore, and EndOfGame within your code, you were calling functions that you defined later. The first enclosed code was responsible for generating a random number to simulate die rolls and updating the game's die graphics. The second function, TotalTheScore, contained several lines of logic to determine what the die rolls mean in terms of winnings. The final function, EndOfGame, determined whether the player wanted to quit the game or start a new game. If he did, the function reset the application so that a new game could begin. The next sections explore how this process works.

Returning Data from a Function

One of the easiest aspects to understand about functions is their return type. Functions are often employed to perform tasks and return results. You then can assign these results to a variable, use them to drive a logical test, or use them as a conditional expression to control a loop.

The following code, for instance, illustrates two instances of converting a numeric value to a string so that it can be displayed by the MessageBox::Show method:

 Double dblValue = 10; Int32 intValue = 100; //Convert the double value and assign it to //  a textbox property txtPassword->Text = dblValue.ToString(); //Display the results of the conversion and //  assignment MessageBox::Show( txtPassword->Text ); //Skip the assignment and just show the //  conversion directly MessageBox::Show( intValue.ToString() ); 

Both dblValue and intValue have methods (functions) that automatically convert their value to another data type. In this case, after both variables are declared and initialized, the first, dblValue, initializes the Text property of a text box, txtPassword, that was previously declared elsewhere in the program. Specifically, the value of 10 is returned as a string by dblValue's ToString method. This string is then copied to txtPassword->Text. Next, txtPassword->Text serves as an argument in the MessageBox::Show method, resulting in 10 being displayed in a dialog box.

The display of the value of intValue skips a step, however. Because intValue.ToString returns a string, the data it returns is supplied directly as an argument to MessageBox::Show, which needs at least one string for the application to display a message.

Hint 

An argument is a variable or constant value, such as a number, that is passed to a function. When used within a function, an argument is referred to as a parameter.

The advantage of the first technique is that the contents returned by the method ToString are saved in another variable (txtPassword->Text) and can be used elsewhere. The advantage of the technique used by intValue is that no variable is required. This can be useful if you temporarily need to return a result from a function but don't care about saving that result.

Handling Events

Behind the scenes, Visual C++ invisibly performs numerous steps to make your application functional. The steps include displaying the controls on your application's form and making certain that it functions properly with the Windows operating system. Handling events is yet another aspect that Visual C++ manages seamlessly. In response to user input or other triggers, your application can generate events, which in turn link to program code that you have defined.

Hint 

An event is an occurrence within your application, such as a button click, that can trigger the execution of an associated function if such a function has been defined. If no function has been defined, the event is handled by the code that Visual C++ generates, handled by the operating system, or ignored.

To give your WinForms applications the most basic functionality, you must place code within a function and then associate that code with an event or data relating to the form. If you don't, there is no link between your application code and the functionality of the form. You can see an example of this by creating a project, dragging a button to it, and then running it. When you click on the button, nothing happens because your application does not capture the button click event.

As noted earlier, you have been working with functions in all the chapter projects that you have completed so far in this book. For example, in many of the chapter game projects, you added code to perform tasks that executed when the application was first loaded. To do this, you double-clicked on the game project's form when viewing it in Design view. This caused Visual C++ to automatically generate a Load event function for you, which was then displayed in the Code Editor. A good example of this can be taken from the Dice Poker game's form Load event function, which is shown here:

 private: System::Void Form1_Load(System::Object^\ sender, System::EventArgs^  e) {   //Seed random number generator with current time   DateTime moment = DateTime::Now;   randNumGen = gcnew Random( moment.Millisecond );   // Set starting game variables   pbxDie1->Image = imlDiceList->Images[0];   pbxDie2->Image = imlDiceList->Images[0];   pbxDie3->Image = imlDiceList->Images[0];   pbxDie4->Image = imlDiceList->Images[0];   pbxDie5->Image = imlDiceList->Images[0];   blnExcludeList = false;   intTimerCntr = 0;   //Set starting money   intTotalDollars = 20;   //Set beginning text   txtOutput->Text = \   String::Concat( "Welcome! Are you ready "   "to play Dice Poker?\r\r\nYou have ",   intTotalDollars.ToString(),   " dollars in your account." ); } 

If you go back and look at the rest of the code in the Dice Poker game, you'll see that it is organized inside various functions. Most of these are events, which are generated as a result of your double-clicking on form controls in Design view.

Defining Custom Functions

Now that you have a better understanding of what functions are and what they can do, let's look at creating one. To create a function, you first must give it a unique name. The rules for naming functions are basically similar to variables: They must begin with a letter, and they can contain letters and numbers.

Trick 

You should strive to give your function a name that reflects the task it performs. This makes your code read more like English, which will be easier to follow as you begin to add more functions.

After you have a name for the function, you must decide if you want it to return data. You also must determine if the function should accept data. The usage of the function differs based on these choices, but fortunately, the format for defining it is the same.

The format for defining a function is as follows. Each element that makes up the function is shown in brackets for better clarity:

 [public | protected | private]: [Return Type] FunctionName ([params]) {   function body   .   .   . } 

The first component of the function definition, which specifies whether it is public, protected, or private, relates to Object-Oriented Programming. As such, it is discussed more thoroughly in Chapter 9, "Getting Comfortable with Object-Oriented Programming." For now, you should know that the first component determines whether other modules can see and use the function.

The next element of the function, the return type, specifies the type of data that the function returns. You are free to use most of the data types, such as Int16, Int32, Double, or Void. Some data types, such as the String type, have special considerations, so you should avoid using them until you have a better understanding of handles (discussed briefly later in this chapter). Also, note that by declaring the return type of your function to be Void, you indicate to Visual C++ that your function will return no data.

The next element of the function definition is the function name. This is followed by the parameter list (shown in the previous example as params). You can indicate that your function will accept no data or one or more pieces of data. If your function accepts no data, you must specify Void in the parentheses following its name. If you want to accept data, you must place the variable type and name that will be used inside the function. You can specify multiple variable names and types by separating each with a comma.

To understand this better, let's look at some examples:

 private: System::Void Form1_Load(System::Object^\ sender, System::EventArgs^  e) {   InitiateGame();   SetStartingMoney( intStartingMoney );   SetStartingMoney( 200 );   blnSuccess = CheckSignIn(); } 

In this sample listing, a call is made to several functions when the application's Load function is called. First, a Load function calls a function that neither accepts nor returns data, called InitiateGame. Next, SetStartingMoney is called and passes as an argument a variable, defined elsewhere, called intStartingMoney. Just to illustrate parameter passing, this function is called again, using a constant value of 200 rather than a variable.

Finally, a function called CheckSignIn is called, which accepts no data but returns a Boolean value. This return value is assigned to the blnSuccess variable. Note that if you specify a function as having a return type other than Void, you must use the keyword return to return a value that matches the data type. Failing to do so generates an error.

Here is a basic example of how you can define these functions:

 private:Void InitiateGame( Void ) {   blnGameInitialized = true;   btnStart->Enabled = true; } private:Void SetStartingMoney( Int32 intMoney ) {   intGameMoney = intMoney; } private:Boolean CheckSignIn( Void ) {   return false; } 

In this example, the first function, InitateGame, indicates that it does not accept data because both its return type and list of arguments are Void. Instead, it sets a Boolean value, blnGameInitialized (defined elsewhere), and enables one of the application's buttons. The second function, SetStartingMony, assigns the intGameMoney variable (defined elsewhere in the program) to the parameter called intMoney. This enables it to accept any Int32 value, which can be a variable or a number. The last example, CheckSignIn, returns false, a Boolean value.

image from book
IN THE REAL WORLD

Although this example would not be very functional, it illustrates a process called stubbing, which is a popular technique that programmers use to get an application up and running quickly. Stubbing functions involves defining all the functions that an application will use but giving the interior of those functions the minimal code they need to work. It allows an application to be put together in a skeletal fashion, with code being quickly added after the overall structure is defined.

image from book




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net