-
Any code that doesn't call constructor at the top of the block can either be
a) rewriten with pointers and dynamic allocation as with nv's example (slow, leak prone even)
b) rewritten so that there is an extra pair of braces not associated with conditional execution (unneccesary).
Is there anyone who didn't come from coding in C, and thus didn't get into the habit of thinking that all variable declarations should be at the top of the block, but who still refrains from ever putting variables in the middle of a block?
-
>>Is there anyone who didn't come from coding in C, and thus didn't get into the habit of thinking that all variable declarations should be at the top of the block, but who still refrains from ever putting variables in the middle of a block?
Yes I did.
I just think it helps the code to make more sense.
I hate going through other peoples code and suddenly finding some new identifier and having no idea where its come form.
-
It seems simple to me... If the variable is going to be used throughout the entire function, then its declared at the top of the function. If the variable is going to be used only once or in a small and specific area of the function (like for a for loop, error checking, etc) then it gets declared where its used. I would find it horribly disturbing to see:
for(i = 0; i < l_ThisNumber; i ++)
...and not instantly know what 'i' was. It better damn well not be a short if you know what i mean...
-
>>> I would find it horribly disturbing to see:
I wouldn't, that is what I would expect to see! If you code in several languages, you use a style that fits all of them. I always know where my variables are declared.
-
Coding in a style that fits all langauges prevents you from exploiting the advantages of any.
-
>>> prevents you from exploiting the advantages of any.
In this thread we were talking about the definition place for variable. Since C++ is the only one of the languages I use that allows the definition in random places, I don't believe it is a big sacrifice.
I don't believe the ability to declare variables all over the place is an advantage. I've never worked in a professional house where it was done.
-
>I don't believe it is a big sacrifice.
Hey I agree with that, especially since nothing is gained by it [nor do the rules for variable declaration say we must abide by it]. In fact, I support the former since it organizes your variable per scope, and prevents redeclaration of variables as well.