How to store a C++ variable in a register

后端 未结 8 2091
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 23:26

I would like some clarification regarding a point about the storage of register variables: Is there a way to ensure that if we have declared a register variable in our code,

8条回答
  •  醉梦人生
    2020-12-15 23:39

    Generally it's impossibly. Specifically one can take certain measures to increase the probability:

    Use proper optimization level eg. -O2

    Keep the number of the variables small

    register int a,b,c,d,e,f,g,h,i, ... z;  // can also produce an error
    // results in _spilling_ a register to stack
    // as the CPU runs out of physical registers
    

    Do not take an address of the register variable.

    register int a;
    int *b = &a;  /* this would be an error in most compilers, but
                     especially in the embedded world the compilers
                     release the restrictions */
    

    In some compilers, you can suggest

    register int a asm ("eax");  // to put a variable to a specific register
    

提交回复
热议问题