Wednesday, June 25, 2008, 11:54 AM - Programming
Did you know that C++ allows you to declare variables anywhere in the code and not necessarily at the beginning of the function? Of course you do! If you dont you are at the wrong place in the internet. Get away from my blog --- Shoooooooo!Most C++ programmers who come from C background, however many times prefer to declare variables in the beginning of the function. They say its their style. They say it makes code look better. They don't want to have variable declarations scattered all around. If you are among them, think again. This feature was not introduced for mere flexibility of a programmer's style.
Your program is likely to perform better if you delay the declaration of your variable as late as possible.
An object/variable in a function may be unused because of a possible early exit, an if-then-else condition or because of an exception. Declaring late avoids unnecessary constructions of objects which may not be used in the function.
Moreover by declaring all objects, destructors of the unused objects are called unnecessary.
Additional tip:
If you face a compiler error is declaring an object inside a "case" of a switch statement use an extra "{" "}" pair as shown below:
switch(action) {
case WRITE:
Writer writer;
int x;
writer.Write("Some stuff");
break;
case READ:
Reader reader;
reader.Read(data);
break;
default:
break;
}You may get an error saying "initialization of 'writer' is skipped by 'case' label" if you have defined a constructor for Writer or Reader class. The fix is below:
switch(action) {
case WRITE:
{
Writer writer;
int x;
writer.Write("Some stuff");
}
break;
case READ:
{
Reader reader;
reader.Read(data);
}
break;
default:
break;
}Happy Programming.//




( 3.1 / 34 )


Calendar




