Variable Declaration & Initialization :: C++

Status
You're currently viewing only PsychoOne's posts. Click here to go back to viewing the entire thread.
Not open for further replies.
I prefer to declare my variables at the top, but that's juts a carry-over from my ANSI-C days.

One thing to watch out for is that while the variables of simple types have no initialization cost, the objects do, because for every declaration of an instance, a constructor is involved. So, if there is any chance that an object may not be used at all, it's declaration should be left until the last moment. Example
code:<HR>
Code:
void Example(int i)
{
    ...
    if( i == 0 )
    {
        MyObject Obj;
        Obj.DoStuff();
    }
    else
        cout << "i != 0\n";
}

By not declaring Obj at the top of the function, you may have saved non-trivial CPU time required to initialize said object, in case i was not equal to 0.

Other than the considerations above, I am of the opinion that if you have to struggle to remember which variables you declared at the top, your function is too long anyway. But it's all semantics.

PO
 
Status
You're currently viewing only PsychoOne's posts. Click here to go back to viewing the entire thread.
Not open for further replies.