Can this statement ever evaluate to 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 in general looks solid and it's hard for me to believe that the only purpose of this snippet is to confuse reviewers, but I don't see a way for this condition开发者_运维百科 to fail. Am I missing something?
This may be a remnant of a nullable type. See here at msdn for an explanation, but basically if your code was originally this:
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 this could possibly fall through. Each of the statements above would be false, as n could be null
from the function, assuming it returned null on a bad input, and the code supported nullable types.
Unlikely, but when looking at "maintained code" anything is possible. But as written, it MUST return 1 (or throw an exception, as mentioned by others in this thread).
It will always return true, assuming it gets there.
Consider:
bool x = (n > 0) || (n < 0);
bool y = (n == 0);
if (x || y)
{
return 1;
}
If n
is not zero then either n > 0
or n < 0
is true, so x
is true and y
is false.
If n
is zero, n == 0
is true, so x
is false and y
is true.
Either way, one side of the OR is true.
That sure looks like a 100% true statement to me. All those parentheses shouldn't matter in the least, since || is associative, i.e.,
(a || b) || c == a || (b || c) == a || b || c
If you overload the relational operators for your class, it might be the case that the condition evaluates to false
, but since n
is an int
, it always evaluates to true
It's possible that int n = Convert.ToInt32(text);
could throw an exception, in which case the if statement never even gets evaluated.
See Convert.ToInt32() on MSDN.
As above, it will always be true because, by definition, any real number is either zero, less than zero or greater than zero, and you have covered all cases in your code.
Always will be 1, unless Convert.ToInt32(text)
throws an exception.
I don't see how it can evaluate to false.
If, however, n
was declared at a different scope where more than a single thread had access to it and one of these threads changes its value, theres quite a high chance the condition would fail.
it will always be true as you write all the states it might be (e.g < > ==)
Yes, it could also throw an exception if the conversion fails :-)
精彩评论