gpt4 book ai didi

c - 使用指针会取消关联变量的 "register"属性吗?

转载 作者:太空狗 更新时间:2023-10-29 16:42:43 25 4
gpt4 key购买 nike

在 C 中,指针的使用会取消关联变量的“注册”属性吗?

#include<stdio.h>
#include<stdlib.h>
int main()
{
register int clk=0; //maybe register maybe not
int *adr=&clk; //not a register now? i have its address
*adr=1; //if i use this 1000000 times, does it exist in L1 at least?
printf("%d",clk);
return 0;

}

给出编译器错误“无法获取寄存器变量的地址”,但它不是寄存器 %100。这只是一个机会。

这是最慢的循环吗?

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
int i=0;
p=&i;
for(*p=0;(*p)<100;(*p)++)
{
//do nothing
}
printf("%d ",i);
return 0;

}

如果我将几乎所有变量都设为指针样式,并且只有三个变量是带有“register”关键字的原始类型,编译器是否更有可能使这三个变量“真正注册”?

好的。问题解决了。我学习了一些汇编,发现这取决于优化级别和变量的波动性。使用 __asm{} 确保它在寄存器中计算。谢谢。

最佳答案

在 C 中,将 & 应用于使用 register 说明符声明的变量是非法的。

6.7.1

The implementation may treat any register declaration simply as an auto declaration. However, whether or not addressable storage is actually used, the address of any part of an object declared with storage-class specifier register cannot be computed, either explicitly (by use of the unary & operator as discussed in 6.5.3.2) or implicitly (by converting an array name to a pointer as discussed in 6.3.2.1).

和 6.5.3.2:

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

对于C++,如果你将&与register一起使用,它就取消了它的意义:

ANSI C does not allow for taking the address of a register object; this restriction does not apply to C++. However, if the address-of operator (&) is used on an object, the compiler must put the object in a location for which an address can be represented. In practice, this means in memory instead of in a register.

关于c - 使用指针会取消关联变量的 "register"属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11393300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com