Is it good practice to initialize variable to nil
?
I'm asking that because when I run the analyzer on my project I get a warning.
NSString *q;
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
{
sqlite3_step(statement);
selectedQuestion =[NSString stringWithFormat: @"%s",(char *)sqlite3_column_text(statement, 0)];
sqlite3_finalize(statement);
}
sqlite3_close(database);
return q; //Undefined or garbage value returned to caller
When I change the code the warning is gone:
NSString *q = nil;
Summary. Start with a clean slate: Uninitialized variables are a common source of bugs in C and C++ programs. Avoid such bugs by being disciplined about cleaning memory before you use it; initialize variables upon definition.
A variable must always be initialized before use. Normally, the compiler gives a warning if a variable is undefined. It is then sufficient to take care of such cases. Instances of a class are usually initialized even if no arguments are provided in the declaration (the empty constructor is invoked).
Declaring variables without initialization lead to logical errors which are hard to debug sometimes. So to avoid this, we write it like this int sum = 0; We declared variable 'sum' and initializated it to 0 to avoid any error.
Variables are initialized to null by default.
If you are using ARC then your pointers will automatcially be assigned to nil. However, I don't believe you are using ARC in which case the pointer will have a garbage value. This is dangerous because whoever called the function could receive the result and believe the pointer points to something valid since it isn't equal to nil.
So... Yes, always initialize your pointers to nil or a valid value.
Example 1 :: Good example where assigning to nil first is not neccessary:
UIViewController *myVC = [[[UIViewController] alloc] init] autorelease];
Example 2 :: Bad example where assigning to nil first is not neccessary:
UIViewController *myVC = nil; // dumb since next line assigns it to valid value
myVC = [[[UIViewController] alloc] init] autorelease];
Example 3 :: Good example of assigning to nil since it will conditionally get a new value
UIViewController *myVC = nil; // :D
if (someCondition)
{
myVC = [[[UIViewController] alloc] init] autorelease];
}
...
Yes. If q is not initialized to nil, it will have a random value, which may introduce hidden bugs in later execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With