Traps of comparing variables, numbers

Experienced C coders who already understand the difference between assignment and comparison but are prone to making typos might be helped by that. But this trap is normally fallen into by those with less or no experience, and they often don't even know the difference between compiler warnings and errors, or how to enable the output of warnings.

@PaulRB: I agree with that.

Meanwhile I remembered what my mistake was last year.

This code is incorrect!

int test_int = -1;

if (test_int > 0u)
{
  //do something if test_int positive
}

I compared an integer value to 0u to see whether it is positve or not.

But this always evaluates to true if test_int is not zero. I guess, because of the sign (most significant) bit which is set when test_int is negative.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.