Search code examples
objective-ciosnullclang-static-analyzer

Is it good practice to initialise a variable to nil?


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;

Solution

  • 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];
    }
    ...