How to Solve C Programming Problems with printf() and puts() - dummies

How to Solve C Programming Problems with printf() and puts()

By Dan Gookin

When you can’t figure out what’s going on with a C program and you don’t want to run it through the debugger (or when you didn’t include the debugging build option), you can use the printf() and puts() functions as your debugging friends.

How to document problems

Suppose that the code has a function that receives variable x, but somehow, variable x never shows up. Insert the following line into the code:

printf("value of 'x' at Line 125: %dn",x);

This statement may actually appear in several places, tracing the value of variable x as it moves through your code. Granted, using the Watches window with the debugger on would be better, but, sometimes, using printf() is a lot quicker.

If you’re not tracking a variable and you only want to know why a chunk of code isn’t executing, insert a puts() statement, something like this:

puts("You got to here");

When you see the preceding text in the output, you know that the code is being approached but still may not be executed. That’s when you talk through the code, look for a double-equal sign when you meant to use a single equal sign, and try out other tricks.

Though inserting a printf() or puts() statement into your code may not be as graceful as using a debugger, and it certainly doesn’t say, “The problem is right here,” it’s not a bad work-around. Just remember to pull the statements back out again!

How to save comments for future-you

Another thing you can do to help fix undue woe is simply to describe the problem in the code by using comments. It may not fix the problem now, but for future-you looking at the code down the line, it’s a real help; it beats trying to discover the boo-boo all over again.

For example:

for(y=x+a;y<c;y++)  /* this doesn’t seem to work */
  manipulate(y);  /* Confirm that a is changing */

In this example, the note reminds future-me that the statements aren’t doing what they’re intended; plus, it offers future-me a suggestion on what to look for in a solution.

You can also use comments to offer future-you suggestions on how to improve the code, things to tighten up, or new features you just don’t have time to add presently.