Monday, 19 January 2015

How to avoid "assignment instead of comparison "

Almost every beginning C programmer independently rediscovers
the mistake of writing:

if (i=3)

instead of:

if (i==3)

Once experienced, this painful error (doing an assignment where comparison was intended) is rarely
repeated. Some programmers have developed the habit of writing the literal first, like this:

 if (3==i)

Then, if an equal sign is accidentally left out, the compiler will complain about an
"attempted assignment to literal." This won't protect you when comparing two variables, but every

little bit helps.

No comments:

Post a Comment