问题描述
在下面的代码中,
int main( )
{
register int arr[4];
/* ... */
}
'arr' 是否有可能在某个 cpu 寄存器中分配.(考虑 cpu 有 4 个或更多寄存器).
Is it possible that 'arr' is allocated in some cpu register.(Consider cpu has 4 or more registers).
否则编译器将忽略 register 数组的存储类.
Or compiler will ignore register storage class for array.
推荐答案
据我了解,答案是YES和NO.
没有因为,
任何数组元素都必须是可显式寻址的(例如,对于 16 位 uC/uP,其地址应始终位于 0x0000 到 0xFFFF 地址空间之间.)
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.)
使用 register direct 寻址模式(例如 mov r2,#100 )访问 CPU 寄存器.这种寻址方式没有有效地址.(即使它不被认为是一种寻址模式)
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 )
数组元素必须驻留在连续的内存位置.(对于指针运算,使用数组的主要原因)
Array elements must reside in continous memory locations. ( for pointer arithmetic, the main reason to use array )
并且是的因为,
- 编译器可以为上面的数组分配寄存器,这样我们就可以对它进行一些有限的操作.但不能使用内部使用地址进行优化的操作.
见下面的代码.
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;
}
所以我的最终结论是,理想情况下,register 存储类不应该与 array 一起使用,即使您的编译器允许这样做.
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. :-)
这篇关于是否可以将整个数组保存在 cpu 寄存器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!