Jump to content

Introduction to Programming/Debugging

From Wikiversity

Using an IDE makes debugging easier as you can look at the variable values as they change. However, that isn't something that works everytime you need it. The solution is a trick programmers have used for decades. You put debugging print statements in.

To demonstrate this, I'm going to use a pseudo language similar to C, C++, Java, Python, Kotlin, and many others. This will output 3 values on a line nicely formatted for me:

print("location",value1,value2)

Assignments will be with one = and comparisons will be with two ==. Your initial code looks like:

index = 0
while (index < 10)
{
    if (index = 5)
    {
    }
    else
    {
        print(index)
    }
    index = index+1
}

You expected output of 0 to 4 and 6 to 9. But instead, your program runs and doesn't output anything. Put in some print statements like this:

index = 0
print("before while",index)
while (index < 10)
{
    print("top of loop",index)
    if (index = 5)
    {
        print("inside if true",index)
    }
    else
    {
        print(index)
    }
    index = index+1
    print("bottom of loop",index)
}
print("after while",index)

The outputs will easily point out the missing = of the if statement as the huge amounts of 5 and 6 values get outputted. You can limit the output seen by using a debug flag to allow output:

if (debug)
{
    print("location",value)
}

This code can be left in your finished product just in case somebody reports a bug, after you make it public, so you don't have to recreate it.

Complex conditions can be used to turn on the debugging or an array of debug flags can be used. For example output a debug message every ten times a function is called, to discover the bug is between the 50th and 60th time. Add debugging that gets turned on, once the 50th call is made, to display a bit more information for those calls finding out the 56th call is the problem.

Put detailed debugging in for just that execution to display everything as it happens and discover exactly what line of code must change.