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

Recommended Answers

All 7 Replies

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.

commented: +++++++++ +1

Even if the variable is only one and doesn't take much space???)) (Eg 1 byte)

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.

commented: +++++ +1

that is, you mean that the value of the register can be changed by some other program?

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.

I just meant this keyword )

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.