[A89] Re: Variables in C
[Prev][Next][Index][Thread]
[A89] Re: Variables in C
> If you were to declare the variable as a global variable, it would be
> stored in the global variable stack for the remainder of the program.
This is
> by far faster because no time is lost during execution by moving the
content
> of the variable to a stack repeatedly. The problem, however, is that a
global
> sprite would make your program bigger. A way around this is declaring the
> variable as "static", or declaring all of your sprites locally and then
moving
> them into a global struct (which is what I do whenever I have a lot of
sprites
> to manage), or a struct type definition. For example, you could do either
> this:
Jude, you are once again COMPLETELY WRONG in this half of your post!
1.) There is no such thing as "the global variable stack." Global variables
are NOT stored on the stack; they're stored within the program's file and
access to them is fundamentally different from local variables on the stack.
You are correct that using global variables would be faster here, but the
wrong reason, and your logic does not correctly extend to the general case
(writing to global variables is much less efficient than writing to local
variables, as writes to globals can't be PC-relative and thus require
entries in the relocation table, greatly bloating executable size -- the
real reason globals are faster here is that this data is only read from,
never written to).
2.) Making the sprite global will make the program SMALLER, NOT BIGGER! In
fact, the original poster made that observation in his post. With a global
sprite, you need only the global data. With a local sprite, you need a
global copy of the initial data, plus the code within the function to load
it locally onto the stack. This is always true for sprites, but note that
it isn't always true for other kinds of variables/data. In some cases,
global variables that are written to a lot will bloat the program size a
lot, because of the abovementioned relocation table entries required.
3.) Declaring the variable as static is NOT a correct workaround and a VERY
BAD IDEA. The static keyword is complicated, and while it will eliminate
the bloat here, it has side effects that you don't realize and still isn't
the optimal solution. The correct answer is to declare the array const (at
which point global or not is irrelevant, but convention is to make it global
because that extends its scope without any cost).
4.) Your "declar[ing] sprites locally and then moving them into a global
struct" is just wrong and makes no sense whatsoever. I don't know what the
hell you're thinking, but I'm not going to try to figure it out. This
advice is bizarre and just plain wrong.
The original poster would be well advised to ignore Jude's advice and refer
instead to my earlier post, which gives a correct explanation and solution.
-Scott