Harry the hacker Harry the hacker - 2 months ago 7
C++ Question

Whats the benefit of initializing your variables late in the function than at the start of a function body?

Ive been reading a excellent book written by Bjarne Stroustrup and he recommends that you declare variables as late as possible, preferable just before you use it, however it fails to mention any benefits over declaring the variables late than at the start of the function body.

So what is the benefit of declaring variable late like this:

int main()
{
/* some
code
here
*/
int MyVariable1;
int MyVariable2;
std::cin >> MyVariable1 >> MyVariable2;
return(0);
}


instead of at the start of a function body like this:

int main()
{
int MyVariable1;
int MyVariable2;
/* some
code
here
*/
std::cin >> MyVariable1 >> MyVariable2;
return (0);
}

Answer

Suppose, that you deal with some objects and construction of these objects is an expensive operation. In such situation there are a few reasons why it is better to define variables just before their usage:

1) First of all, it is sometimes faster to create an object using appropriate constructor instead of default-constructing and assignment. So this:

T obj(/* some arguments here */);

may be faster then this:

T obj;
/* some code here*/
obj = T(/* some arguments here */);

Note that in the first example only a single constructor is invoked. But in the second example default constructor and assignment operator are invoked.

2) If an exception is thrown somewhere between object definition and its first usage you just do unnecessary work creating and destroying your object without any usage at all. The same is applicable when function returns between object definition and its first usage.

3) Yes, readability is also worth to mention here :)

Comments