Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 425
objlv Avatar asked Feb 09 '12 17:02

objlv


People also ask

Is it good practice to initialize variables?

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.

Should you always initialize variables?

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).

Why do we initialize variables to 0?

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.

Can you initialize a variable to null?

Variables are initialized to null by default.


2 Answers

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];
}
...
like image 94
Sam Avatar answered Oct 05 '22 06:10

Sam


Yes. If q is not initialized to nil, it will have a random value, which may introduce hidden bugs in later execution.

like image 28
ZelluX Avatar answered Oct 05 '22 07:10

ZelluX