0% found this document useful (0 votes)
56 views

Using The Xcode® Debugger: Objectives

The document discusses using the Xcode debugger to debug programs. It describes setting breakpoints, continuing execution, and using the step into, step over and step out commands to control program flow. Example code of an Account class is provided and breakpoints are set to examine a withdrawal amount variable.

Uploaded by

Maha Imtiaz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Using The Xcode® Debugger: Objectives

The document discusses using the Xcode debugger to debug programs. It describes setting breakpoints, continuing execution, and using the step into, step over and step out commands to control program flow. Example code of an Account class is provided and breakpoints are set to examine a withdrawal amount variable.

Uploaded by

Maha Imtiaz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Using the Xcode® Debugger J

And so shall I catch the fly.


—William Shakespeare

Objectives
In this appendix you’ll:
■ Set breakpoints and run a
program in the debugger.
■ Use the Continue program
execution command to
continue execution.
■ Use the Auto window to view
and modify the values of
variables and watch
expression values.
■ Use the Step Into, Step Out
and Step Over commands to
control execution.

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
J-2 Appendix J Using the Xcode® Debugger

J.1 Introduction J.4 Controlling Execution Using the


J.2 Breakpoints and the Continue Step Into, Step Over and Step Out
program execution Command Commands
J.3 Auto Window J.5 Wrap-Up

J.1 Introduction
In Chapter 2, you learned that there are two types of errors—compilation errors and logic
errors—and you learned how to eliminate compilation errors from your code. Logic errors
(also called bugs) do not prevent a program from compiling successfully, but can cause the
program to produce erroneous results when it runs. Most C++ compiler vendors provide
software called a debugger, which allows you to monitor the execution of your programs
to locate and remove logic errors. The debugger will be one of your most important pro-
gram development tools. This appendix demonstrates key features of the Xcode debugger.

J.2 Breakpoints and the Continue program execution


Command
We begin our study of the debugger by investigating breakpoints, which are markers that
can be set at any executable line of code. When program execution reaches a breakpoint,
execution pauses, allowing you to examine the values of variables to help determine wheth-
er a logic error exists. For example, you can examine the value of a variable that stores the
result of a calculation to determine whether the calculation was performed correctly. Note
that attempting to set a breakpoint at a line of code that is not executable (such as a com-
ment) will actually set the breakpoint at the next executable line of code in that function.
To illustrate the features of the debugger, we use the program listed in Fig. J.3, which
creates and manipulates an object of class Account (Figs. J.1–J.2). Execution begins in
main (lines 10–27 of Fig. J.3). Line 12 creates an Account object with an initial balance of
$50.00. Account’s constructor (lines 9–21 of Fig. J.2) accepts one argument, which spec-
ifies the Account’s initial balance. Line 15 of Fig. J.3 outputs the initial account balance
using Account member function getBalance. Line 17 declares a local variable with-
drawalAmount, which stores a withdrawal amount read from the user. Line 19 prompts the
user for the withdrawal amount, and line 20 inputs the amount into withdrawalAmount.
Line 23 subtracts the withdrawal from the Account’s balance using its debit member
function. Finally, line 26 displays the new balance.

1 // Fig. J.1: Account.h


2 // Definition of Account class.
3 class Account
4 {
5 public:
6 Account( int ); // constructor initializes balance
7 void credit( int ); // add an amount to the account balance

Fig. J.1 | Header file for the Account class. (Part 1 of 2.)

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Using the Xcode® Debugger J-3

8 void debit( int ); // subtract an amount from the account balance


9 int getBalance(); // return the account balance
10 private:
11 int balance; // data member that stores the balance
12 }; // end class Account

Fig. J.1 | Header file for the Account class. (Part 2 of 2.)

1 // Fig. J.2: Account.cpp


2 // Member-function definitions for class Account.
3 #include <iostream>
4 using namespace std;
5
6 #include "Account.h" // include definition of class Account
7
8 // Account constructor initializes data member balance
9 Account::Account( int initialBalance )
10 {
11 balance = 0; // assume that the balance begins at 0
12
13 // if initialBalance is greater than 0, set this value as the
14 // balance of the account; otherwise, balance remains 0
15 if ( initialBalance > 0 )
16 balance = initialBalance;
17
18 // if initialBalance is negative, print error message
19 if ( initialBalance < 0 )
20 cout << "Error: Initial balance cannot be negative.\n" << endl;
21 } // end Account constructor
22
23 // credit (add) an amount to the account balance
24 void Account::credit( int amount )
25 {
26 balance = balance + amount; // add amount to balance
27 } // end function credit
28
29 // debit (subtract) an amount from the account balance
30 void Account::debit( int amount )
31 {
32 if ( amount <= balance ) // debit amount does not exceed balance
33 balance = balance - amount;
34 else // debit amount exceeds balance
35 cout << "Debit amount exceeded account balance.\n" << endl;
36 } // end function debit
37
38 // return the account balance
39 int Account::getBalance()
40 {
41 return balance; // gives the value of balance to the calling function
42 } // end function getBalance

Fig. J.2 | Definition for the Account class.


© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
J-4 Appendix J Using the Xcode® Debugger

1 // Fig. J.3: figJ_03.cpp


2 // Create and manipulate Account objects.
3 #include <iostream>
4 using namespace std;
5
6 // include definition of class Account from Account.h
7 #include "Account.h"
8
9 // function main begins program execution
10 int main()
11 {
12 Account account1( 50 ); // create Account object
13
14 // display initial balance of each object
15 cout << "account1 balance: $" << account1.getBalance() << endl;
16
17 int withdrawalAmount; // stores withdrawal amount read from user
18
19 cout << "\nEnter withdrawal amount for account1: "; // prompt
20 cin >> withdrawalAmount; // obtain user input
21 cout << "\nattempting to subtract " << withdrawalAmount
22 << " from account1 balance\n\n";
23 account1.debit( withdrawalAmount ); // try to subtract from account1
24
25 // display balances
26 cout << "account1 balance: $" << account1.getBalance() << endl;
27 } // end main

Fig. J.3 | Test class for debugging.

Opening the Xcode Project for This Appendix


We’ve included an Xcode project (Debugging.xcodeproj) for the code from Figs. J.1–J.3
in the appJ/Debugging folder with this book’s examples. In the Mac OS X Finder, navi-
gate to
Documents/examples/appJ/Debugging

and double click the Debugging.xcodeproj to open the project’s workspace window in
Xcode.
Inserting Breakpoints
In the following steps, you’ll use breakpoints and various debugger commands to examine
the value of the variable withdrawalAmount declared in Fig. J.3.
1. Inserting breakpoints. Click figJ_03.cpp in the Project navigator to display the
file in the Xcode Editor area. To insert a breakpoint, click inside the gray bar to
the left of the line of code at which you wish to break. You can set as many break-
points as necessary. Set breakpoints at lines 17 and 21. A blue arrow appears to
the left of the line where you clicked, indicating that a breakpoint has been set
(Fig. J.4). When the program runs, the debugger pauses execution at any line that
contains a breakpoint. The program is said to be in break mode when the debug-

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Using the Xcode® Debugger J-5

Breakpoints

Fig. J.4 | Setting two breakpoints.

ger pauses the program. Breakpoints can be set before running a program, in
break mode and while a program is running.
2. Starting to debug. After setting breakpoints in the code editor, click the Run ( )
button on the workspace window’s tool bar to build the program and begin the
debugging process. When you debug an application that normally runs in a Ter-
minal window, you can see the program’s output and provide input in the Debug
area below the Editor area in the workspace window (Fig. J.5). The debugger en-
ters break mode when execution reaches the breakpoint at line 17.
3. Examining program execution. Upon entering break mode at the first breakpoint
(line 17), the IDE becomes the active window (Fig. J.5). The green arrow to the
left of line 17 indicates that this line contains the next statement to execute.
4. Using the Continue program execution button to resume execution. To resume ex-
ecution, click the Continue program execution ( ) button in the Debug area’s
toolbar, which resumes program execution until the next breakpoint or until the
program terminates, whichever comes first. The program continues executing
and pauses for input at line 18. Enter 13 as the withdrawal amount. The program
executes until it stops at the next breakpoint (line 21). Notice that when you
place your mouse pointer over the variable name withdrawalAmount, the value
stored in the variable is displayed in a yellow tooltip below the mouse cursor
(Fig. J.6). As you’ll see, this can help you spot logic errors in your programs.

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
J-6 Appendix J Using the Xcode® Debugger

Next line of code to execute is highlighted in green You interact with the application in this part of the Debug area

Fig. J.5 | Inventory program suspended at first breakpoint.

Green arrow shows next Debug area toolbar Tooltip showing variable value
statement to execute

Fig. J.6 | Quick Info box showing the value of a variable.

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Using the Xcode® Debugger J-7

5. Completing the program’s execution. Click the Continue program execution ( )


button to complete the program’s execution. The result of the program’s calcu-
lation is shown in the Debug area (Fig. J.7).

Fig. J.7 | Program output.

6. Removing a breakpoint. Right click the breakpoint and select Delete Breakpoint.
7. Finishing program execution. Select Debug > Continue to execute the program to
completion.
In this section, you learned how to enable the debugger and set breakpoints so that
you can examine the results of code while a program is running. You also learned how to
continue execution after a program suspends execution at a breakpoint and how to remove
breakpoints.

J.3 Auto Window


In this section, you’ll learn to use the Auto window to watch variable and expression values
and to assign new values to variables while your program is running.
1. Inserting breakpoints. Clear the existing breakpoints. Then, set breakpoints at
lines 21 and 24 of figJ_03.cpp.
2. Starting to debug. Click the Run ( ) button on the workspace window’s tool bar
to build the program and begin the debugging process. Type 13 at the Enter with-
drawal amount for account1: prompt and press Return so that your program reads
the value you just entered. The program executes until the breakpoint at line 21.
3. Suspending program execution. The debugger pauses at line 21. At this point, line
18 has input the withdrawalAmount that you entered (13), lines 19–20 have out-
put that the program will attempt to withdraw money and line 21 is the next
statement that will execute.
4. Examining data. The left side of the Debug area displays the Auto window by de-
fault. This window automatically shows variables that are currently in scope—the
icon indicates that a variable is a local variable. This window allows you to ex-
plore the current values of variables. Click the arrow to the left of account1 in the
Name column of the Locals window. This allows you to view each of account1’s
data member values individually—this is particularly useful for objects that have
several data members. Figure J.8 shows the values for main’s local variables
account1 and withdrawalAmount (13).

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
J-8 Appendix J Using the Xcode® Debugger

Auto Window

Fig. J.8 | Examining the variables that are currently in scope.

5. Evaluating arithmetic and boolean expressions. You can watch the values of spe-
cific variables, arithmetic expressions and boolean expressions using the Auto
window. To do so, right click in the Auto window and select Add Expression….
In the small window that appears, type the variable or expression to watch. For
example, enter the expression (withdrawalAmount + 3) * 5, then press Return.
The expression’s type and value (80 in this case) are displayed to the right of the
expression (Fig. J.9). Repeat this to add the expression withdrawalAmount == 3,
then press Return. Expressions containing the == operator (or any other relational
or equality operator) are treated as bool expressions. The value of the expression
in this case is false (Fig. J.9), because withdrawalAmount currently contains 13,
not 3. The icon indicates that a line in the Auto window represents an expres-
sion that you are watching. When configuring a variable or expression to watch,
if you check the Show in All Stack Frames checkbox, the expression will be dis-
played in the Auto window throughout the debugging process; otherwise, the ex-
pression will be displayed only in the scope where you created the expression. You
can delete a watched expression by right clicking it and selecting Delete Expres-
sion.

Evaluating an arithmetic expression Evaluating a bool expression

Fig. J.9 | Examining the values of expressions.

6. Resuming execution. Click the Continue program execution ( ) button to re-


sume execution. Line 21 debits the account by the withdrawal amount, and the
debugger reenters break mode at line 24. The updated balance in account1 is
now displayed in italic blue text (Fig. J.10) to indicate that it has been modified
since the last breakpoint.

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Using the Xcode® Debugger J-9

Value of account1’s balance data


member displayed in blue italic text

Fig. J.10 | Displaying the value of local variables.

7. Modifying values. Based on the value input by the user (13), the account balance
output by the program should be $37. However, you can use the Auto window to
change the values of variables during the program’s execution. This can be valu-
able for experimenting with different values and for locating logic errors. In the
Auto window, expand the account1 node, select balance then click its value (37)
to make it editable. Type 33, then press Return. The debugger changes the value
of balance (Fig. J.11).

Value modified in the


Auto window

Fig. J.11 | Modifying the value of a variable.

8. Viewing the program result. Click the Continue program execution ( ) button
to resume execution. The program displays the result. Notice that the result is $33
(Fig. J.12). This shows that Step 7 changed the value of balance from the calcu-
lated value (37) to 33.

Fig. J.12 | Output displayed after modifying the account1 variable.

In this section, you learned how to use the debugger’s Watch and Locals windows to
evaluate arithmetic and boolean expressions. You also learned how to modify the value of
a variable during your program’s execution.

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
J-10 Appendix J Using the Xcode® Debugger

J.4 Controlling Execution Using the Step Into, Step


Over and Step Out Commands
Sometimes executing a program line by line can help you verify that a function’s code ex-
ecutes correctly, and can help you find and fix logic errors. The commands you learn in
this section allow you to execute a function line by line, execute all the statements of a
function at once or execute only the remaining statements of a function (if you’ve already
executed some statements within the function).
1. Removing a breakpoint. Remove the breakpoint at line 24 from Section J.3.
2. Starting to debug. Click the Run ( ) button on the workspace window’s tool bar
to build the program and begin the debugging process. Type 13 at the Enter with-
drawal amount for account1: prompt and press Return so that your program reads
the value you just entered. The program executes until the breakpoint at line 21.
3. Using the Step Into command. The Step Into command executes the next state-
ment in the program (line 21), then immediately halts. If that statement is a func-
tion call (as is the case here), control transfers into the called function. This
enables you to execute each statement inside the function individually to confirm
the function’s execution. Click the Step Into ( ) button in the Debug area’s tool-
bar to enter the debit function. The green arrow indicating the next statement
to execute is positioned at line 31 of Account.cpp.
4. Using the Step Over command. Click the Step Over ( ) button to execute the
current statement (line 31) and transfer control to line 32. The Step Over com-
mand behaves like the Step Into command when the next statement to execute
does not contain a function call. You’ll see how the Step Over command differs
from the Step Into command in Step 8.
5. Using the Step Out command. Click the Step Out ( ) button to execute the re-
maining statements in the function and return control to calling function (line
21 in Fig. J.3). Often, in lengthy functions, you’ll want to look at a few key lines
of code, then continue debugging the caller’s code. The Step Out command en-
ables you to continue program execution in the caller without having to step
through the entire called function line by line.
6. Completing the program’s execution. Click the Continue program execution ( )
button to complete the program’s execution.
7. Starting the debugger. Before we can demonstrate the next debugger feature, you
must start the debugger again. Start it, as you did in Step 2, and enter 13 in re-
sponse to the prompt. The debugger enters break mode at line 21.
8. Using the Step Over command. Click the Step Over ( ) button. This command
behaves like the Step Into command when the next statement to execute does not
contain a function call. If the next statement to execute contains a function call,
the called function executes in its entirety (without pausing execution at any state-
ment inside the function), and the green arrow advances to the next executable
line (after the function call) in the current function. In this case, the debugger ex-
ecutes line 21, located in main (Fig. J.3). Line 21 calls the debit function. The

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Using the Xcode® Debugger J-11

debugger then pauses execution at line 24, the next executable line in the current
function, main.
9. Stopping the debugger. Click the Stop button on the Xcode toolbar.
In this section, you learned how to use the debugger’s Step Into command to debug
functions called during your program’s execution. You saw how the Step Over command
can be used to step over a function call. You used the Step Out command to continue exe-
cution until the end of the current function.

J.5 Wrap-Up
In this appendix, you learned how to insert, disable and remove breakpoints in the Xcode
debugger. Breakpoints allow you to pause program execution so you can examine variable
values. This capability will help you locate and fix logic errors in your programs. You saw
how to use the Auto window to examine the value of an expression and how to change the
value of a variable. You also learned debugger commands Step Into, Step Over, Step Out
and Continue program execution that can be used to determine whether a function is exe-
cuting correctly.

© 2014 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

You might also like