-6

When I read experienced programmers code, I realize some patterns which I would not consider optimized code. I've been searching for this on google but there's no discuss on the topic that I could find.

What is the reason behind declaring all variables at the beginning of the program? For example, why does someone use:

GtkWidget *window;

gtk_init(NULL, NULL);

window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

instead of

gtk_init(NULL, NULL);

GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

Or, for example, why does one declare a variable i for a loop like

int i;
char *a;

(code)

for(i = 0; i < n; i++)

instead of declaring i just above the for loop?

char *a;

(code)

int i;
for(i = 0; i < n; i++)

I think it would be easier to read. Isn't that just giving away memory? Because until the time the for is called, there are 4 bytes in memory which are not used.

I'm not remembering other patterns that I use to see in others code but I find very often things like this that I'd like to know why are like this; specially if they are not optimized (I guess). I asked some people why they do things like this but they either tell me they were taught like that or they get offended like I shouldn't have asked that.

I genuinely interested in knowing why do programmers structure their code like this in order to understand and improve my coding. And if you have any advice on how to structure code or tips on good programming behaviours, please let me know.

tvaz
  • 97
  • 1
  • 10
  • 3
    Please explain [tag:c] or [tag:c++], this is very different in each language. One of the major differences. Declaring variables at the beginning of a block improves readability a LOT, a whole LOT. – Iharob Al Asimi Jan 19 '16 at 15:43
  • I do program in both languages, so I'm looking to answers from people of both backgrounds to apply on my code. But isn't someone sacrificing memory usage to readability? – tvaz Jan 19 '16 at 15:48
  • I can't guess the reason for everyone, but some old languages actually required to make all variable declarations in the start of the function block. Maybe they just learned to code a very long time ago. Of course, this is just random guessing. – Not a real meerkat Jan 19 '16 at 15:50
  • 1
    @CássioRenan Yes incuding old [tag:c] standard. – Iharob Al Asimi Jan 19 '16 at 15:50
  • @iharob, yup, that too. – Not a real meerkat Jan 19 '16 at 15:51
  • @CássioRenan: Start of function or start of block? These are different concepts. pre-C99 e.g. allowed declarations at the start of a block, not only a function. – too honest for this site Jan 19 '16 at 15:55
  • @Olaf, I'm aware, but my comment is not restricted to C. I just thought I should use a more language agnostic "example". It's still just guessing, and shouldn't be treated as a definite (or even fully correct) answer. – Not a real meerkat Jan 19 '16 at 15:59
  • @CássioRenan: I anticipated that. But actully many imperative languages follow that idea. – too honest for this site Jan 19 '16 at 16:01
  • ... and do you consider yourself to write optimized code? Proof please. Also, why even declare `int i` before the `for(i; ; i++)` when you can do `for(int i; ; i++)` Sometimes code grows these fuzzy hairballs because, maybe just maybe, they fixed the problem somehow. As far as memory usage goes, in non-embedded systems, noone will die because of 4 byte allocation a few instructions before they're *really* needed. – Shark Jan 19 '16 at 16:03
  • 2
    the only "memory" this is costing you is disk space to hold the source file. and if you are going to worry about that then make your variable names and function names shorter, get rid of carriage returns and line feeds and other wasteful white space. – old_timer Jan 19 '16 at 16:04
  • @dwelch ah, suggestion the F77 (fortran) pattern of naming I see. good one, haven't seen that in a while. – Shark Jan 19 '16 at 16:05

4 Answers4

4

Isn't that just giving away memory? Because until the time the for is called, there are 4 bytes in memory which are not used.

I don't think so. In the common platforms that I have worked in, Linux and Windows, the size of the stack frame is same regardless of whether you declare the variables at the top of the function or declare them as you go.

The only scenarios where declaring the variables at the top of the function will have an adverse impact is if the construction of the object is expensive.

Whether you declare them at the top of the function or declare them as you need is, most of the time, a policy decision in a development team.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Older versions of C (K&R C, C89) required all variables to be declared before any code within a block. It wasn't until the C99 standard that declarations could be mixed with code (C++ obviously did that a bit earlier). As for why that was the case, remember that C is a product of the early 1970s, when 256 kilowords was a lot of memory and processor speeds were orders of magnitude slower than they are today. Anything that simplified parsing and code generation was a Good Thing, and forcing you to group declarations together helped with that (note that many of C's contemporaries like Fortran and Pascal also forced all declarations to occur that the beginning of a function or a block).

As for memory, most compilers will generate code to allocate the storage for all block-scope objects at function entry, regardless of where the declaration actually occurs in the source code. IOW, the two snippets

int i;
// bunch of code here
for ( i = 0; i < 10; i++ ) 
  do_something_interesting();

and

// bunch of code here
for ( int i = 0; i < 10; i++ ) 
  do_something_interesting();

will (most likely) result in the same machine code that allocates the space for i at function entry.

The only real advantage in deferring declarations (in C, anyway) is to make the code easier to read and maintain. It has little to no effect on runtime performance (compilers may optimize a little differently based on where things are declared, but IME that doesn't happen much).

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • Fortran doesn't force you to declare variables at all, if I'm not mistaken. However, in Pascal (and other languages that descend from Algol60) the strict separation of variable declarations and code holds true until today - and presumably this still has its advantages (apart from readability). Think static checkers that prove conformance to a certain coding style, for instance. – morido Jan 19 '16 at 20:09
  • @morido: Strictly speaking, that's true about Fortran - it allows (allowed?) for implicit declarations. It's just that I had `IMPLICIT NONE` beaten into me from the beginning, and if you *are* going to explicitly declare a variable, it has to be done before any executable statement. – John Bode Jan 19 '16 at 20:13
0

Any decent optimizing compiler would reduce the effective lifetime of the int or pointer in the cases you described in order to achieve any performance improvements made possible by that reduced lifetime.

So the early declaration is bad C++ style (and bad C style in modern version of C). But you would need a more difficult example for that bad style to produce less efficient code.

Someone reading the code does not have as much memory as a compiler so any variable whose declared lifetime exceeds its useful lifetime is a source of confusion to anyone trying to understand your code. Worry about that first, and (most of the time) let the compiler writers worry about the performance.

JSF
  • 5,281
  • 1
  • 13
  • 20
  • Why are "*early declarations*" bad style in [tag:c]? They improve readability a lot. – Iharob Al Asimi Jan 19 '16 at 16:01
  • Any function long enough to have enough variables or code to exhaust the readers memory is bad style. – Iharob Al Asimi Jan 19 '16 at 16:02
  • @iharob this is not the right place for this debate, but you are very much wrong about the readability of early declarations. – JSF Jan 19 '16 at 16:03
  • it's a matter of taste, some have bad taste and some others have good taste. I have seen code of very good software written by really talented developers and they all disagree with you. – Iharob Al Asimi Jan 19 '16 at 16:04
  • It is not a matter of taste. It is a matter of competence and experience. You are advocating a style that increases errors and makes code harder to understand. – JSF Jan 19 '16 at 16:11
  • Oh so writing short concise functions that do just one thing is a style that increases errors and makes code harder to understand. You said no debate. I don't know how much experience you have, but I can tell from my experience, that this *style* is best. No more comments please, this is more an opinion based topic. Although you should also consider that the preference of the majoirty of developers should be good because otherwise it wouldn't be the preference of the majority of developers. – Iharob Al Asimi Jan 19 '16 at 16:19
  • @iharob You put false words in my mouth and then request "No more comments please"! Obviously there would be no point trying to convince you of the harm of early declarations. But I hoped to mitigate the harm your bad advise will do to less experienced programmers reading this. – JSF Jan 19 '16 at 16:25
-1

from http://www.dummies.com/how-to/content/declaring-variables-in-c.html: "That way, the compiler knows what the variables are called and what type of variables they are (what values they can contain)"

I think this post is relatable : Where you can and cannot declare new variables in C?

Community
  • 1
  • 1
  • While this may answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Panda Jan 19 '16 at 15:51
  • I don't think this is an answer because the quote above implies that the poster didn't understand the question. The OP does understand that variables MUST be declared, the confusion is to why experienced programmers declare them at the top of a block or function. – Iharob Al Asimi Jan 19 '16 at 15:53
  • Thank you for your suggestion! This is actually my first response on stackoverflow and have no idea on what people expect in their answers. I will be more carefull next time. – Didier Lauwerys Jan 19 '16 at 15:58