| .NET DotNet Forum Index » Visual C# Forum » Trap on returned value... |
|
Page 1 of 1 |
|
| Author |
Message |
| Jason... |
Posted: Thu Oct 29, 2009 7:29 pm |
|
|
|
Guest
|
Hello
I've got a function that will return a ninteger value. If that value is
anything other then 1, 2, 4 I need to report an error
so how would I do this?
I've rtn = function();
if((x != 1) || (x != 2) || ( x != 4))
{
// report error
}
Is this correct logic? |
|
|
| Back to top |
|
|
|
| Family Tree Mike... |
Posted: Thu Oct 29, 2009 7:43 pm |
|
|
|
Guest
|
Jason wrote:
Quote: Hello
I've got a function that will return a ninteger value. If that value is
anything other then 1, 2, 4 I need to report an error
so how would I do this?
I've rtn = function();
if((x != 1) || (x != 2) || ( x != 4))
{
// report error
}
Is this correct logic?
No, because x is always _not_equal_ to at least two of those three
numbers. Do this:
if (!((x == 1) || (x == 2) || (x == 4))) // return error
--
Mike |
|
|
| Back to top |
|
|
|
| Rudy Velthuis... |
Posted: Thu Oct 29, 2009 8:35 pm |
|
|
|
Guest
|
Jason wrote:
Quote: Hello
I've got a function that will return a ninteger value. If that value
is anything other then 1, 2, 4 I need to report an error
so how would I do this?
I've rtn = function();
if((x != 1) || (x != 2) || ( x != 4))
{
// report error
}
Your logic is a little bit off: if x == 1, then the first test will be
false, but the second and third true, so an error will be reported.
Just make it:
if (x != 1) && (x != 2) && (x != 4)
{
// report error
}
--
Rudy Velthuis http://rvelthuis.de
"Incorrect documentation is often worse than no documentation."
-- Bertrand Meyer |
|
|
| Back to top |
|
|
|
| Peter Duniho... |
Posted: Thu Oct 29, 2009 10:37 pm |
|
|
|
Guest
|
Jason wrote:
Quote: Hello
I've got a function that will return a ninteger value. If that value is
anything other then 1, 2, 4 I need to report an error
so how would I do this?
I've rtn = function();
if((x != 1) || (x != 2) || ( x != 4))
{
// report error
}
Is this correct logic?
Others have pointed out the error in the above, and described correct
boolean expressions to achieve the correct results. For readability,
you might consider a switch statement instead:
switch (x)
{
case 1:
case 2:
case 4:
// do whatever;
break;
default:
// report error
break;
}
This works well for relatively few valid numbers, such as your scenario.
A less readable, but theoretically more efficient method is to count bits:
if (x > 4 || (x & (x - 1) != 0))
{
// report error
}
For only three valid values, actually that's obviously not more
efficient. But you can extend it to arbitrarily many valid set bits (by
increasing the "4" to match whatever the maximum bit you expect) and it
will work.
Obviously the bit-counting approach only works if your set of valid
numbers is in fact all powers of two.
Pete |
|
|
| Back to top |
|
|
|
|