简体   繁体   中英

GCC register optimization

Hi I was interested in what assembly code will gcc generate from this code (this is just dummy code to illustrate my point):

int a = 0;
int foo(void)
{
    int result = a;
    a += 2;
    return result;
}

I was surprized that gcc copies the variable a to the stack and then from the stack to a register so it can return it. When I added register to the declaration of result, it optimized the code not to use the stack but instead to copy the variable directly to a register. I know this doesn't really make any difference but I was wondering is there any good reason why gcc doesn't make such optimization implicitly. I hope I made it clear what I am talking about...

Any ideas?

When compiling Debug builds (ie, with optimizations off), compilers tend to make very straightforward, easily debuggable code. In this case, it might mean keeping all variables in memory / stack, rather than in registers.

Try compiling with full optimizations (-O3) and see if that makes a difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM