Mike
Mike

Reputation: 737

value of Bool in Objective C

The value of BOOL in objective C is always NO(by default). But recently I encountered a case where the value of BOOL variable was returning YES (by default). Can anybody explain this to me ?

Upvotes: 4

Views: 6587

Answers (2)

iDevAmit
iDevAmit

Reputation: 1578

If you declare a variable without initialization, the OS will allocate memory randomly and at that instant allocated memory may contain some garbage value. That garbage can represent No also or may be Yes value.

Recommended: Always declare a variable with proper initialization to avoid bugs in your code.

Upvotes: 1

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81848

BOOL has no value as it is a type.

You probably mean variables of type BOOL. There are different types of variables, which have different initialization semantics:

  1. Instance variables: Objective-C's alloc promises to set all instance variables to zero, which in case of BOOL means NO;
  2. Global variables: Or, more precisely, variables with static storage duration are initialized to zero, as defined in the C standard.
  3. Local variables are not initialized. If you don't assign a value, their contents are unspecified. This is also from the C standard and probably what you stumbled upon.

Upvotes: 23

Related Questions