Monday, 26 March 2012

A Common Error In C & C++

In C and C++ there’s a difference between the = assignment operator and the == logical equality operator. In many other languages, the equal sign is used in both situations; therefore, it’s easy to use = when you want to use ==.

You compiler won’t tap you on the shoulder to tell you made a mistake. It will happily chug along. There is no syntax error. The problem happens when you run the program. Besides, assigning the value to the variable, I tested some code to see what would happen.

Take this scenario.

     int a = 0;
     if (a = 1){…

First the program will assign 1 to a then it will evaluate the expression a as being non-zero (i.e., not false) and execute any code for the true condition.

This code

     if (a = 0){…

assigns zero to a and results in a false condition.

Similar events happen with the do and while loops.

How about a for loop like this?

     for (i = 0; a = i; ++i) {…

Since a equals i equals 0, it’s false and the for loop doesn’t execute any code under its control.

On the other hand, this code,

     for (i = 1; a = i; ++i) {…

creates an infinite loop. Be ready to hit break.

It’s the easiest mistake to make in C and C++ especially if you’re working with other languages at the same time.

1 comment: