[A89] Re: Variables in C


[Prev][Next][Index][Thread]

[A89] Re: Variables in C



> I was wondering, is it faster (more efficient) to declare global variables
> *once* outside a function, rather than redeclare them every time the
> function is run? For example, which would be better to do between the two
> following codes below if they were used very often...

Declaring the data as _const_ unsigned short will probably make your two
examples generate (almost) equivalent code here.  Without the const
modifier, the data has to be stored somewhere where it can be altered.  If
the array is global, then a single copy of the data can be included in the
program and altered directly.  If the array is local, then it is going to be
stored on the stack; the compiler will need to include a copy of the initial
data in the array, and then after reserving the stack space the program will
copy the initialized array data into the local copy of the array, thus
explaining the size increase.

On the other hand, if the const modifier is used, it doesn't matter if the
data is local because it doesn't have to be alterable, so both examples will
generate the one copy stored within the program, and there will be no need
to make a local copy.  In some cases the second example, modified to use
const, may store the two pointers to the array data locally on the stack,
but that's very different from copying all of the array data to the stack.

Since this is const data that's going to be handled by the compiler by just
sticking a global copy of it in the final executable, convention is to
declare it globally rather than locally.  Conceptually, there's never going
to be a local copy of the data, so why write your C code so it would give
that impression?  And declaring it as a global makes clear that _any_
function can use it, and there's no reason not to use it in other functions
if appropriate, because there's no added cost to doing so.

    -Scott