开发者

Which variable should be optimize in following C code

开发者 https://www.devze.com 2023-02-17 08:21 出处:网络
If your compiler a开发者_如何转开发ctually optimizes access time of only two registers variables per function, which two variable in the following program are the best one to be made into register var

If your compiler a开发者_如何转开发ctually optimizes access time of only two registers variables per function, which two variable in the following program are the best one to be made into register variables?

void main(void)
{
  int i,j,k,m;
  do
  {
    printf("enter value");
    scanf(“%d”,&i);
    m=0;
    for(k=0;k<100;k++)
      m=k+m;
  }
  while(i>0);
}

Please ignore if any mistake is there...


Trick question? In a smart compiler, none of the variables are registerized. i has its address taken, so it can't be in a register all the time. j, k and m should be optimized away.


Certainly not j, since it is never used. Not i either, as you are using the address-of operator to write to it, which means it needs to be read back from memory after it's been written by the scanf. That only leaves k and m.


Good compiler will optimize this part of code:

m=0;
for(k=0;k<100;k++)
  m=k+m;

And replaced it with m = 4950; :) The better one will optimize m = 4950; and put nothing in place). j also will be optimized. And i can't be register because in scanf its address is needed. So final answer is "NO ONE".


I'd guess the compiler would pick k and m


Since the result of the computation is never used the compiler can optimize out almost all of your code. The only things that must remain are equivalent to

int main(void) {
  int i;
  do {
    printf("enter value");
    scanf(“%d”,&i);
  } while(i>0);
  return 0;
}

As others have already said the only remaining variable i can't be of register storage class since its address is taken.

0

精彩评论

暂无评论...
验证码 换一张
取 消