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?
source to share
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).
source to share
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.
source to share
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.
source to share