Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 749
Rahul Chawre Avatar asked Jun 27 '13 12:06

Rahul Chawre


People also ask

Can array be stored in register?

An array in C or C++ can be placed in a register explicitly if it is allocated memory statically and its memory is not accessed.

What is register array in CPU?

Register array consists of registers identified by letters like B, C, D, E, H, L and accumulator. The control unit controls the flow of data and instructions within the computer.

What are the types of CPU registers explain use of each CPU register?

The instruction read from memory is placed in the Instruction register (IR). The Temporary Register (TR) is used for holding the temporary data during the processing. The Input Registers (IR) holds the input characters given by the user. The Output Registers (OR) holds the output after processing the input data.


2 Answers

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. :-)

like image 168
Rahul Chawre Avatar answered Nov 09 '22 14:11

Rahul Chawre


Don't mix register as a keyword with CPU registers. Your code

register int arr[4];

makes that arr is completely inaccessible, since you can't take the address of the object. Basically the only thing that you can do with it is sizeof arr.

like image 23
Jens Gustedt Avatar answered Nov 09 '22 13:11

Jens Gustedt