1

I am reading a value from a byte stream and want to assert that this value is within an enums range. I was wondering if there's a more generic approach than the one below.

int nval = ReadValue();
Assert(nval);

bool Assert(nval)
{
 if(nval == zero || nval == one || nval==two || (nval>=reserved_low && nval <= reserved_high))
  return true;
 return false
}
    enum Foo
    {
     zero = 0,
     one = 1,
     two = 2,
     reserved_low = 3,
     reserved_high = 255,
    }
tzippy
  • 6,458
  • 30
  • 82
  • 151

2 Answers2

1

Not in C++03, no.

Your way is pretty optimal (and certainly readable), although you could recognise that, given all your enums are in the range 0 to 255, return !(nval & ~0xff); would do the job.

You might be able to squeeze out a bit more performance using a switch and compare nval>=reserved_low && nval <= reserved_high in the default case.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I wouldn't have thought that those optimizations would make much of a difference; the original code is pretty simple, so the compiler would probably do a better job of optimizing it than we would. – TartanLlama Aug 22 '16 at 11:31
  • It would be interesting to see if the compiler did collapse it to `!(nval & ~0xff)` – Bathsheba Aug 22 '16 at 11:32
  • The above version (when fixed) just gets a `cmpl` followed by a `setbe` from [GCC](https://godbolt.org/g/KS4GcZ). – TartanLlama Aug 22 '16 at 11:33
1

Here is a similar but slightly cleaner trick:

enum Foo {
 zero = 0,
 one = 1,
 two = 2,
 reserved_low = 3,
 reserved_high = 255,
 foo_count
};

bool Assert(nval) {
  if(nval > zero && nval < foo_count) {
    return true;
  }
  return false;
}

Because enum increments each entry with 1, count will now be set to value 256. If you would add extra valid values later on count will automatically be updated.

Sander
  • 861
  • 7
  • 15