I have been up against a bug in my furnace monitor Arduini code for two days. The first night I looked for it I had had a rough day at work. My mind was spent. Last night (although it did take a while) I found the bug. It was a classic mix up between a == comparison and an = assignment operator. The statement I had wanted was
if (val == 0xffff) {
What I ended up with was always setting val to 0xffff and always taking the branch. How I wish that C would not have allowed assignments inside conditional clauses. Some people would hate having to write code that was “wordy”, but it would have saved the world much frustration.
I need to find a good Lint program…
The classic way to avoid this bug once and forever, is to teach yourself to write these conditions the other way round:
if( 0xffff == val) {
if( null != test) {
etc.
when (not if) you use = instead of ==, the compiler gives you a nice error, as you can’t assign to constants.
*X*
Nice idea. I will see if I can train myself to not code with ==. Or I was thinking of using a #define to define EQUALS to ==. Now if I use the macro name, I can’t screw up. Or perhaps figure out a way to run Lint on the code. Lint will flag a single equals in an if statement as a likely error.
You’re right, that is a practice that will reduce the chance of error. However, for some reason it doesn’t feel aesthetically pleasing to me. When comparing a variable to a constant, I like to read the expression “if x equals 5”, not “if 5 equals x”.
Call me odd, but I like my code to read a certain way. Don’t worry! You can have your cake and eat it too. gcc is your friend:
$ cat assignment_or_comparison.cpp
int check_value(int x)
{
if (x = 2) // (!!!)
return 1;
else
return 0;
}
$ g++ -c assignment_or_comparison.cpp
$ g++ -Wall -c assignment_or_comparison.cpp
assignment_or_comparison.cpp: In function ‘int check_value(int)’:
assignment_or_comparison.cpp:3:14: warning: suggest parentheses around assignment used as truth value [-Wparentheses]