Monday, May 04, 2009

C++: "=" vs. "=="

In C or C++, a mistake that is often made is to use "=" where you actually mean "==". Today was such a day... For demonstration purposes, consider the following function:

void myFunction(int myInput)
{
printf("myInput = %d\n", myInput);
assert((myInput =1) || (myInput = 2));
printf("myInput = %d\n", myInput);
}

At the beginning of the function we want to check if the input is valid by using assert. When you call this with myFunction(2) you get:

myInput = 2
myInput = 1

myInput becomes 1 although we called the function with the value of 2. The bug is caused by careless use of "=". We should use "==" for comparisons. "=" means assignment. The correct form should be:

assert((myInput == 1) || (myInput == 2));

Bug catching tip: write const before myInput so that the compiler will complain when you try to change myInput inside the function:

void myFunction(const int myInput)

So, when we call the buggy function we get (with Visual Studio 2003)

error C2166: l-value specifies const object

Which will be a wake up call.

No comments: