Archived

This topic is now archived and is closed to further replies.

Limiting Variable Scopes

This topic is 5155 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi there, I''m want to know if it''s better to limit local variables scope as much as possible using an additional block within the function. here''s an example(this example uses BCB RunTime Library)
void func1()
{

// initialize query variable

{
AnsiString temp;					// because these variables aren''t needed below, they were

unsigned short day, month, year;	// put in these block.

date.DecodeDate(&year, &month, &day);

temp.printf("SELECT *\n"
"FROM %s\n"
"WHERE CustomerFile = %d AND\n"
"	   DATEPART(month, CustomerFileDate) = %d AND\n"
"	   DATEPART(year, CustomerFileDate) = %d", ViewName.c_str(), id, month, year);

}

SetupConnection(query);

// the rest of the function

// ...

}

I know that the compiler Generates ENTER and LEAVE instructions for blocks, and AFAIK they are expensive instructions (if I''m wrong please correct me!) so which is better, leaving them in the function scope although they are not needed except for 1/4 of the function in terms of lines of code. xee.. Speed is not the only thing that matters, Quality does TOO!

Share on other sites
You should always put the decleration of the var right before it is used. Example:

int Function() {    int a = 1;    if(a == 1) {        int b = 2;        cout << b << endl;    }    return 0;}

int Function() {    int a = 1;    int b = 2;    if(a == 1) {        cout << b << endl;    }    return 0;}

I read about this in Efficient C++ (A book). Forget the reason why. This is quite contrary to C-style programming (which, vars have to be on top).

[edited by - MetaCipher on April 11, 2004 12:05:11 AM]

Share on other sites
its because you delay constuction of objects until the point you need them (not really an issue with ints i guess ) and also allows you to pair construction with intialisation (sp?) which cuts down on the work the computer has to do.
MyObj a;a = b;

causes a to be default constructed and then assigned (which you see when people are used to programing the ''C way'') where as doing it all in one line means you get a construction with the value you want, cuts down on a function call at least.

Share on other sites
The reason for keeping scope as small as possible is not performance. It is code maintainability. It leads to fewer programmer errors.

In my experience, programmer time is much more expensive than CPU time, so it''s better generally to minimse it even if it makes a less efficient program.

Because you don''t declare a variable before you need it, you can''t accidentally use it for something else, or forget to initialise it, etc, if it was 50 lines above.

Mark

Share on other sites
In classic C, you declare things with the creation of a new stack frame, indicated by curly braces, so, the example:
int a=1;if (a==1){  int b = 2;}
This is completely valid C code. Plus, b only exists in that scope. This is great with GNU compilers wich allow macros to pretty extensible.
#define ABS( x ) ({int _x = x; if(_x<0){_x=-_x;}_x})

That looks confusing, but it creates a temporary stack frame and temporary variable _x that only exists in that frame.

Of course, these days I''d just suggest inline functions, which might be a nice way to deal with scope as well.

Share on other sites
May be I haven't been clear enough, none of the 4 replies answered my questions, so I'll state them clearly:
- Is it true that blocks are converted by the compiler to stack frames using ENTER, LEAVE instructions.
- I'm asking about performance impact(I think that by limiting the variable scope, the compiler can make use of it) nothing else. However, thanks for markr for his worthy note.

[edited by - xeee on April 12, 2004 1:41:52 PM]

Share on other sites
quote:
Original post by markr
The reason for keeping scope as small as possible is not performance. It is code maintainability. It leads to fewer programmer errors.

This is one of the few times when performance and maintainability do somewhat mesh, for the construction/destruction/assignment reasons noted above by myself (based on Item 32; Postpone Varible definitions as long as possible, of Effective C++ by Scott Meyers).

@Xeee
1 - Personaly i''ve never heard of an ENTER and LEAVE instruction with regards to C++ or assembler (x86 or 68000), afaik the scoping is just pretty much instructions to the compiler that things will only exist in this block of code and to clean up once done.

2- Performance wise, you can gain by limiting the construction of large objects until you are sure you need them, allowing you to short cut out of a function for example without having to construct and destroy an unneeded stack based class (which, depending on the class in question the cost could range from trival to expensive). However, code clarity should always be your defineing code guide until such time as its proven that you need a performance boost.
I''m guessing the example listed used the varibles in a different scope because they didnt, for what ever design reason, want to keep those varibles in scope, thus freeing up their names for later use in the function.

• 39
• 15
• 9
• 23
• 10