views:

102

answers:

2

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 ?

+1  A: 

Perhaps someone redefined their values?

#define YES (BOOL)0
#define NO  (BOOL)1
Alex Reynolds
+7  A: 

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 undefined. This is also from the C standard and probably what you stumbled upon.
Nikolai Ruhe
#3 is what I was going to post as well!
Wevah
Does that mean that int a will NOT always give value 0 in Objective C ?
mindfreak
@Mindfreak: exactly. All local (function scope) variables always have to be initialized.
Nikolai Ruhe
+1 for point 3 which is almost certainly the problem underlying the questioner's question.
JeremyP
@Mindfreak - In fact, I believe the latest version of the Clang Static Analyzer will warn you about the potential use of uninitialized variables, helping to point out these potential bugs.
Brad Larson