Hi guys) Please tell me - why is it impossible to keep global variables in C in a processor register?
thanks in advance)

7 Years
Discussion Span
Last Post by vedro-compota

The reason is that there are only a limited finite number of resigers available to the program. For example on Intel and compatible processors there are only 6 register variables in common use throught the program (eax,ebx,ecx,edx,esi and edi), so it would be impossible to store global variables in them.

Edited by Ancient Dragon: n/a

Votes + Comments

A value is a value, and any appropriate value can be place in a register, but if the global variable's value changes and something reliant on it is only being given the value from the register; then the value in the global is no longer the same as the one given to the register and anything receiving the value through the register is now out-of-date.

So that would be an issue if you were to do that, of course as mentioned above - there's only limited registers, and those registers can also be altered long before you get back to them, since they're only very temporary storage.

Edited by MosaicFuneral: n/a

Votes + Comments

Unless you're writing this program in pure assembly, the compiler is going to make use of those registers without your consent. You can try working against the compiler with the inline assembler and fancy tricks while reading the the compiler's assembly output and continuously altering code to work with it, but that's impractical.


In C and C++ there is a register keyword, but most (if not all) compoilers just ignore it for reasons previously stated. And even then register can not be used with global variables.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.