Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to create an array using register storage class in C?

As we know that address of the variable declared with register storage class can't be taken. So i tried to create an array with register keyword and tried to access the element . but i noticed that there is no any error raised by compiler.

#include <stdio.h>
void main()
{
   register int x[]={3,4};
   printf("%d\n",x[0]); // compiled successfully
  // printf("%d",&x[0]);// compiler raises an error
}

as we all know that compiler converts the expression x[0] to *(x+0) where x represents the base address. But how is it possible to get the base address of the array since it is declaraed with register storage class?

Thanks in Advance..

like image 644
Abhishek Jaiswal Avatar asked Apr 12 '21 02:04

Abhishek Jaiswal


1 Answers

Under the C standard, you are allowed to declare an array with register storage class, but it's basically useless; any attempt to use that array to form a pointer, much less to dereference that pointer (to access an element of the array), causes undefined behavior. C17 (n2176) 6.3.2.1 (3):

Except when it is the operand of the sizeof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type “array of type” is converted to an expression with type “pointer to type” that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

In fact, as emphasized in footnote 123 to 6.7.1 (6), pretty much the only thing you can legally do to a register array is to take sizeof of it.

So your example has undefined behavior; it's completely up to the compiler to decide what to do with it. One reasonable choice, and what yours probably does, is to just ignore the register keyword and treat the array like any other array. This is sensible because modern compilers ignore the register keyword in practically every other situation anyway, and make their own decisions when to optimize a variable into a register or not. The one thing it's not allowed to ignore is an attempt to apply the & operator, because that's a constraint violation by 6.5.3.2 (1), and this explains why you get an error when you try to do that.

like image 141
Nate Eldredge Avatar answered Oct 23 '22 05:10

Nate Eldredge