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.