Can this statement ever be considered FALSE?

I stumbled upon this while doing a review and the author is not available:

int n = Convert.ToInt32(text);
if (((n > 0) || (n < 0)) || (n == 0))
{
  return 1;
}

      

The code looks solid overall, and I find it hard to believe that the sole purpose of this snippet is to confuse the reviewers, but I see no way for this condition to fail. Am I missing something?

+2


source to share


10 replies


This can be the remainder of the nullable type . See here at msdn for an explanation, but mostly if your code was originally the following:

int? n = StringToInt(text);    // People roll their own functions to do this, though
                               // they really shouldn't
if (((n > 0) || (n < 0)) || (n == 0))
{
  return 1;
}

      



Then it might fail. Each of the above statements would be false, since n could be null

from a function, assuming it returned zero on bad input, and the code supported nullable types.

Unlikely, but when looking at "supported code" anything is possible. But as written, it MUST return 1 (or throw an exception, as mentioned by others in this thread).

+9


source


It will always return true, assuming it got there.

Consider:

bool x = (n > 0) || (n < 0);
bool y = (n == 0);

if (x || y)
{
    return 1;
}

      



If n

not zero, then either n > 0

or n < 0

true, so x

true and y

false.

If n

equal to zero, it is n == 0

true, therefore it x

is false and y

is true.

Either way, one side of the OR is true.

+5


source


This looks like a 100% true expression. All these parentheses shouldn't matter, since || associative, that is

(a || b) || c == a || (b || c) == a || b || c

      

+2


source


It is possible that it int n = Convert.ToInt32(text);

could throw an exception, in which case the if statement is not even evaluated.

See Convert.ToInt32 () on MSDN.

+1


source


If you overload relational operators for your class, it might be that the condition evaluates as false

, but since it n

is int

, it always evaluatestrue

+1


source


As above, it will always be true because, by definition, any real number is zero, less than zero, or greater than zero, and you have covered all cases in your code.

0


source


Will always be 1 unless Convert.ToInt32(text)

it throws an exception.

0


source


I don't see how it can evaluate to false.

If, however, it n

was declared in another area where more than one thread was available to it, and one of those threads changes its value, the more likely the condition will fail.

0


source


it will always be right as you are writing all the states that can be (e.g. <> ==)

0


source


Yes, this can also throw an exception if the conversion fails :-)

-1


source







All Articles