Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

c - Is it possible to keep an entire array in cpu register

In below code,

int main( )
{
    register int arr[4];
    /* ... */
}

Is it possible that 'arr' is allocated in some cpu register. (Consider cpu has 4 or more registers).

Or compiler will ignore register storage class for array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per my understanding, answer is YES and NO.

NO because,

  1. Any array element must be explicitly addressable (i.e. for eg. for 16 bit uC/uP its address should always lie between 0x0000 to 0xFFFF address space.)

  2. CPU registers are accessed using register direct addressing mode ( such as mov r2,#100 ). This addressing mode does not have an effective address. ( even it is not considered to be an addressing mode )

  3. Array elements must reside in continous memory locations. ( for pointer arithmetic, the main reason to use array )

and YES because,

  1. Compiler can allocate register for above array, so that we can perform some limited operations on it. But operations which internally uses address for optimizations can't be used.

See below code.

int main( )
{
  register int arr[4];
  int i;

  arr[0] = 10;      /* OK */
  arr[1] = 20;      /* OK */
  arr[2] = 30;      /* OK */
  arr[3] = 40;      /* OK */

  for(i=0;i<4;i++)
    arr[i]=10;    /* Error : "address of register variable 'arr' requested" */

  return 0;
}

So my final conclusion is that, ideally register storage class should never be used with array even if your compiler permits it.

Please correct me or give more inputs. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...