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
2010-07-12 10:06:53
+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:
- Instance variables: Objective-C's
alloc
promises to set all instance variables to zero, which in case of BOOL meansNO
; - Global variables: Or, more precisely, variables with static storage duration are initialized to zero, as defined in the C standard.
- 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
2010-07-12 10:14:59
#3 is what I was going to post as well!
Wevah
2010-07-12 11:08:53
Does that mean that int a will NOT always give value 0 in Objective C ?
mindfreak
2010-07-12 11:12:29
@Mindfreak: exactly. All local (function scope) variables always have to be initialized.
Nikolai Ruhe
2010-07-12 11:22:35
+1 for point 3 which is almost certainly the problem underlying the questioner's question.
JeremyP
2010-07-12 12:34:35
@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
2010-07-12 12:36:03