Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ CPU Register Usage

In C++, local variables are always allocated on the stack. The stack is a part of the allowed memory that your application can occupy. That memory is kept in your RAM (if not swapped out to disk). Now, does a C++ compiler always create assembler code that stores local variables on the stack?

Take, for example, the following simple code:

int foo( int n ) {
   return ++n;
}

In MIPS assembler code, this could look like this:

foo:
addi $v0, $a0, 1
jr $ra

As you can see, I didn't need to use the stack at all for n. Would the C++ compiler recognize that, and directly use the CPU's registers?

Edit: Wow, thanks a lot for your almost immediate and extensive answers! The function body of foo should of course be return ++n;, not return n++;. :)

like image 732
Johannes Avatar asked Dec 02 '09 12:12

Johannes


People also ask

How do I access my CPU registers?

CPU registers are accessed by using the names that are predefined in the assembler. Memory is accessed by the programmer providing a name for the memory location and using that name in the user program.

What is a CPU register used for?

A processor register (CPU register) is one of a small set of data holding places that are part of the computer processor. A register may hold an instruction, a storage address, or any kind of data (such as a bit sequence or individual characters). Some instructions specify registers as part of the instruction.

Is CPU register a memory?

Registers are the memory locations that the CPU can access directly. The registers contain operands or the instructions that the processor is currently accessing. Registers are the smallest data storage unit integrated into the CPU.


1 Answers

Yes. There is no rule that "variables are always allocated on the stack". The C++ standard says nothing about a stack.It doesn't assume that a stack exists, or that registers exist. It just says how the code should behave, not how it should be implemented.

The compiler only stores variables on the stack when it has to - when they have to live past a function call for example, or if you try to take the address of them.

The compiler isn't stupid. ;)

like image 129
jalf Avatar answered Oct 02 '22 02:10

jalf