On importance of paying attention.

As I have written in my earlier. I am now reading Bjarne’s introductory book on programming. While doing some of the exercises, I have made an error which many beginners make while debugging. I would like to share it with you today.

It might sound just like simple common sense, but when chasing for errors by reading code it is really important to pay attention to small details. Often code that looks “right” is actually very wrong. One symbol can matter.

Consider the following code. It is supposed read an input of letters and digits into string s.

string s;
while(cin.get(ch) && (isalpha(ch) || isdigit(ch))) s = ch;

When reading the code quickly you just assume that it does what it is
supposed to do and keep reading to the next line.
Brain automatically interprets s = ch as s += ch. However instead of
reading the whole input into s it just reads the last character into s.
To fix this code we need to replace

while(cin.get(ch) && (isalpha(ch) || isdigit(ch))) s = ch;

with

while(cin.get(ch) && (isalpha(ch) || isdigit(ch))) s += ch;

And then everything works as it should.
Such errors are hard to find for inexperienced programmers. (Can not talk for experienced, not there yet 🙂 ).

How can we prevent them? I am not sure, but I believe that not putting the assignment at the same line with condition check can reduce the error.

Writing

while(cin.get(ch) && (isalpha(ch) || isdigit(ch)))
    s += ch;

makes the assignment operation more visible in my eyes.

Hence, the chances of one missing it while reading code are smaller.

The most important is still to try to read a code more carefully and never assume that it works.

Code carefully and make less errors! And if you have tips how to prevent such small bugs, feel free to share with me!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s