Have you ever gone through a problem of mistakenly use of assignment operator =
instead of equality operator ==
in conditional statements or comparisons. I am pretty sure you are. This is common error which can lead to unintended behavior in the program, as the intended logic is not executed as expected. In this article, we will explore this error, its consequences and at last its fixes.
Understanding the Misassignment Problem
Consider the following example where a function checks if a given number is divisible by 2:
#include <iostream>
bool isEven(int number) {
if (number = 0) { // Misassignment here!
return true;
} else {
return false;
}
}
int main() {
int input;
std::cout << "Enter a number: ";
std::cin >> input;
if (isEven(input)) {
std::cout << "The number is even." << std::endl;
} else {
std::cout << "The number is odd." << std::endl;
}
return 0;
}
In the isEven
function, there is misassignment problem in the conditional statement if (number = 0)
. Instead of comparing number
with 0
, the assignment operator =
is used, which assigns 0
to number
and then evaluates to false
. As a result, the function incorrectly identifies all numbers