You’ll use the following program for this exercise. Either type it into Visual Studio, or copy it from this book’s web site. Note that this is spaghetti code—you’d never write method calls like this, but that’s why this is the debugging chapter.
using System; namespace Debugging { class Tester { public void Run( ) { int myInt = 42; float myFloat = 9.685f; System.Console.WriteLine("Before staring: value of myInt: {0} value of myFloat: {1}", myInt, myFloat); // pass the variables by reference Multiply( ref myInt, ref myFloat ); System.Console.WriteLine("After finishing: value of myInt: {0} value of myFloat: {1}", myInt, myFloat); } private static void Multiply (ref int theInt, ref float theFloat) { theInt = theInt * 2; theFloat = theFloat *2; Divide( ref theInt, ref theFloat); } private static void Divide (ref int theInt, ref float theFloat) { theInt = theInt / 3; theFloat = theFloat / 3; Add(ref theInt, ref theFloat); } public static void Add(ref int theInt, ref float theFloat) { theInt = theInt + theInt; theFloat = theFloat + theFloat; } static void Main( ) { Tester t = new Tester( ); t.Run( ); } } }
Place a breakpoint in Run( )
on the following line:
System.Console.WriteLine("Before staring: value of myInt: {0} value of myFloat: {1}", myInt, myFloat);
Step into the Multiply( )
method, up to the call to Divide( )
. What are the values of
theInt
and theFloat
at this point?
Run the program again, and when it reaches the
breakpoint in Run( )
, set a
watch on myInt
. Step
through the methods. When does the value of myInt
change?
Set another breakpoint in Add( )
at this line:
theInt = theInt + theInt;
Run the program. How many calls are in the call stack when the program reaches this breakpoint?
The program in this exercise is similar to the first, but it has a logic error. Type this program into Visual Studio, or download it from this book’s web site.
using System; namespace Debugging { class Tester { public void Run( ) { int myInt = 42; float myFloat = 9.685f; System.Console.WriteLine("Before staring: value of myInt: {0} value of myFloat: {1}", myInt, myFloat); // pass the variables by reference Multiply( ref myInt, ref myFloat ); System.Console.WriteLine("After finishing: value of myInt: {0} value of myFloat: {1}", myInt, myFloat); } private static void Multiply (ref int theInt, ref float theFloat) { theInt = theInt * 2; theFloat = theFloat *2; Divide( ref theInt, ref theFloat); } private static void Divide (ref int theInt, ref float theFloat) { theInt = theInt * 3; theFloat = theFloat * 3; Add(ref theInt, ref theFloat); } public static void Add(ref int theInt, ref float theFloat) { theInt = theInt - theInt; theFloat = theFloat - theFloat; } static void Main( ) { Tester t = new Tester( ); t.Run( ); } } }
If you run this program, you will not get the same results as you did in the previous example. Use the debugging tools you just learned about to find the error. Correct the error, and then run the program again to see if the results are correct.