Trap on returned value

  • Thread starter Thread starter Jason
  • Start date Start date
J

Jason

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?
 
Jason said:
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
 
Jason said:
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
}
 
Jason said:
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
Top