0

In my app I have a function that returns a bool from a long long value _flightId which is initially assigned 0. At some point before calling the function below it is usually assigned a value.

@property (nonatomic, assign) long long flightId;

- (BOOL)isReady
{
    return (_flightId);
}

The problem is that sometimes, even tough it is assigned a different value than 0, the function will return 0.

For example:

if _flightId = 92559101 the function will return 1.

If _flightId = 92559104 the function will return 0.

Can somebody explain this behavior?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
freshking
  • 1,824
  • 18
  • 31
  • 1
    Try changing the return line to: `return _flightId == 0 ? NO : YES;` – rmaddy May 16 '14 at 15:24
  • I actually did this, thanks. But I am interested in the background of the problem I explained. – freshking May 16 '14 at 15:27
  • 1
    It's probably an overflow problem. `BOOL` is just a `signed char`. Cramming a `long long` into ` signed char` will cause overflow. – rmaddy May 16 '14 at 15:29

1 Answers1

1

Your BOOL is presumably just defined as an 8 bit int (char) so when you return a long long you're just getting the low order 8 bits of this. The value 92559104 is 0x5845700 which as you can see has the LS 8 bits all set to zero.

You should do an explicit conversion, e.g.

return _flightId != 0;

or the idiomatic:

return !!_flightId;
Paul R
  • 208,748
  • 37
  • 389
  • 560