How much bad can be done using register variables in C++

前端 未结 7 2336
孤城傲影
孤城傲影 2021-02-18 17:07

I just came to know that we can use registers, explicitly in C++ programs. I wonder what if i declare and use all available registers in a single C++ program and run it for cons

相关标签:
7条回答
  • 2021-02-18 17:26

    The compiler will simply ignore the register keyword, so you are not going to run out of registers. It may well ignore it anyway - compilers are typically much better at register allocation than humans.

    0 讨论(0)
  • 2021-02-18 17:27

    The register keyword is only a suggestion to the compiler and can be ignored. Let the compiler do the optimization for you.

    0 讨论(0)
  • 2021-02-18 17:35

    The register keyword indicates to the compiler that the variable does not need to be addressable in main memory. Thus the compiler can be sure that there are no pointers to the value and optimize accordingly.

    • A common misconsception: the register keyword
    • register Keyword (see the non-Microsoft specific part)
    • "register" keyword in C?

    Excessive use of the register keyword is unlikely to have serious negative impact on modern systems. Every thread maintains its own register values during execution, and its register usage will not have any direct impact on other threads. The compiler will either reject or ignore register usage that cannot result in a viable program. Poor register use will at most merely reduce performance and the OS will take no special action.

    0 讨论(0)
  • 2021-02-18 17:35

    All the CPU registers are at the disposal of your program anyway, so there is nothing exceptional in using all of them. OS won't even notice it.

    0 讨论(0)
  • 2021-02-18 17:40

    Only specific number of Registers are available for your C++ program.

    Also, it is just a suggestion for the compiler mostly compilers can do this optimization themselves so there is not really much use of using register keyword more because compilers may or may not follow the suggestion.

    So the only thing register keyword does with modern compilers is prevent you from using & to take the address of the variable.

    To Quote Herb Sutter on this:
    Never write register. It's exactly as meaningful as whitespace

    0 讨论(0)
  • 2021-02-18 17:48

    Als posted a link to Herb Sutter's article on keywords. I agree with Sutter that one should never use register. I disagree with him on whether register is meaningless.

    It is worse than meaningless.

    I have seen code where a variable qualified with register is later used with "&". Code with dozens and dozens of variables qualified with register. And the ultimate doozy, "register volatile foo;"

    Never use "register".

    0 讨论(0)
提交回复
热议问题