Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 565
Dipakkumar Avatar asked Nov 29 '22 11:11

Dipakkumar


2 Answers

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.

like image 43
iDevAmit Avatar answered Dec 12 '22 12:12

iDevAmit


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.
like image 75
Nikolai Ruhe Avatar answered Dec 12 '22 12:12

Nikolai Ruhe