Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ local variables and registers

Tags:

c++

I often saw that compiler put local function variables in registers. And I have a question regarding this.

If I use some class member variable (integral/pointer, etc...) heavily, does it make sense, to temporary copy it to local variable, work with it, and than copy result to class member?

For example (fill one way ptr list):

struct MyClass{

    struct ObjectHolder{
        ObjectHolder* next_free;
    };
    ObjectHolder *next_free = nullptr;

    void fill(){
        ObjectHolder *copy_of_free = next_free ;  // copy to register?

        for (int i = 0; i < capacity; ++i) {
           ObjectHolder &obj = array[i];

           // build chain of pointers
           obj.next_free = copy_of_free;
           copy_of_free  = &obj;
        }

        next_free = copy_of_free;                 // back to memory
    }
}
like image 596
tower120 Avatar asked Jul 11 '14 15:07

tower120


People also ask

Is register a local variable in C?

Register variables are declared inside a function. Internal static variables are similar to auto variables or local variables. Whereas, external static variables are similar to global variables. Register variables are similar to auto or local or internal variables.

Can local variables be stored in registers?

Local variables are stored in registers in most cases, because registers are pushed and poped from stack when you make function calls It looks like they are on stack.

What are register variables in C programming?

Register variables tell the compiler to store the variable in CPU register instead of memory. Frequently used variables are kept in registers and they have faster accessibility. We can never get the addresses of these variables. “register” keyword is used to declare the register variables.

What are local registers?

Local register means a list of properties officially designated as historically significant by the City of Hayward pursuant to a local ordinance or resolution adopted by the City Council.


1 Answers

What you described in your code goes beyond copying of member variables into local variables to enable register placement. In essence, your question illustrates the difference between two approaches:

  1. Fully computing a result locally before writing it to member variables, vs.
  2. Writing intermediate results to member variables as you go through computations.

Your program follows approach #1. It is more robust than #2, because the object remains in a consistent state while the computation is performed.

Approach #1 may give the compiler more opportunities to optimize your code, too. However, this is a secondary effect; your object staying consistent during the computation is more important.

like image 159
Sergey Kalinichenko Avatar answered Oct 05 '22 23:10

Sergey Kalinichenko