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..
Under the C standard, you are allowed to declare an array with
registerstorage 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):In fact, as emphasized in footnote 123 to 6.7.1 (6), pretty much the only thing you can legally do to a
registerarray is to takesizeofof 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
registerkeyword and treat the array like any other array. This is sensible because modern compilers ignore theregisterkeyword 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.