Is it good practice to initialize a variable to zero?

Is it good to initialize a variable to nil?

I ask about this because when I start the analyzer in 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 did not pass:

NSString *q = nil;
+5
source share
4 answers

If you use ARC, your pointers will be automatically set to zero. However, I do not believe that you are using ARC, in which case the pointer will matter to the garbage. This is dangerous because the one who called the function could get the result and thought that the pointer points to something real, since it is not equal to zero.

... , .

1:: , :

UIViewController *myVC = [[[UIViewController] alloc] init] autorelease];

2:: , :

UIViewController *myVC = nil;  // dumb since next line assigns it to valid value
myVC = [[[UIViewController] alloc] init] autorelease];

3:: nil,

UIViewController *myVC = nil;  // :D
if (someCondition)
{
   myVC = [[[UIViewController] alloc] init] autorelease];
}
...
+11

. q nil, , .

+5

, . - , .

0

- . , . , .

, , , , . ( , , , ) . NULL . , , NSString, , :

NSString* result;
if (condition) result = @"True";
else if (otherCondition) result = @"False";
return result;

, undefined. , , , , .

, nil nil , , nil .

. , , . , , .

0

All Articles