Wednesday, September 5, 2007

Assignment Vs. Comparison Trip

A common mistake made by both beginner and experienced programmers alike is to use the assignment operator "=" vs. the comparisson operator "==". It happens to everyone now and then and can make debugging a real pain. People tend to see what they're looking for when reading their own code and this can easily be overlooked. Here's an example.


if($x = true){
//do something
}


since the assignment operator was used, the above statement will always be true thus making the condition useless. where the programmer obviously meant to say


if($x == true){
//do something
}


A simple trip to avoid this problem is getting in the habit of reversing the elements of the comparison like this "if(true == $x)". If the programmer then makes the mistake of using the assignment operator the parser
will throw an error since true cannot receive an assignment.


if( true = $x){
//do something
}


if you slip up, you will know immediately and without any manual debugging.
I hope this is useful and saves you time in coding and debugging.