views:

170

answers:

2

Hello

It is a best practise to initialise a variable at the time of declaration.

int TMyClass::GetValue()
{
    int vStatus = OK;
    // A function returns a value
    vStatus = DoSomeThingAndReturnErrorCode();
    if(!vStatus)
        //Do something
    else
       return(vStatus);
}

In the debug mode, a statement like this int vStatus = OK; is causing no issues during DEBUG MODE build.

The same when build in RELEASE MODE, throws a warning saying w8004: 'vStatus' is assigned a value that is never used.

Also, i am using the same variable further down my code with in the same function,like this if(!vStatus)and also i return the value of return(vStatus);

When i looked at the web for pointers on this debug Vs Release, compilers expect you to initialise your varible at the time of declaring it. Link

I am using Borland developer studio 6 with windows 2003 server.

Any pointers will help me to understand this issue.

Thanks

Raj

+3  A: 

You initialise vStatus to OK, then you immediately assign a new value.

Instead of doing that you should initalise vStatus with a value that you're going to use.

Try doing the following instead:

int TMyClass::GetValue()
{
    // A function returns a value
    int vStatus = DoSomeThingAndReturnErrorCode();
    if(!vStatus)
        //Do something
    else
       return(vStatus);
}

Edit: Some clarification.

Initialising a variable, only to never use that value, and then to assign another value to the variable is inefficient. In your case, where you're just using int's it's not really a problem. However, if there's a large overhead in creating / copying / assignment for your types then the overhead can be a performance drain, especially if you do it a lot.

Basically, the compiler is trying to help you out and point out areas in your program where improvements can be made to your code

Glen
Thanks for your comment. But why does this require a warning. The reason why i declare and initialise at the begining is because, i know what value i have assigned my status variable to.
Raj
Sbi and Msalters have explained the answer to my question in the time when i posted the above comment. Thanks
Raj
Warnings aren't mandated. Instead they are things the compiler writers think are good to bring to your attention. Generally they are good to follow because they will include things like "you forgot a return statement in this function" or "variable x in function foo() hides variable x in the main function."
Max Lybbert
A: 

If you're wondering why there's no warning in debug mode, it's because the passes that perform dataflow analysis (which is what finds the problem) are only run as part of optimization.

me22