问题描述
是否允许在其定义的右侧获取对象的地址,如以下foo()
所示:
Is it allowed to take the address of an object on the right hand-side of its definition, as happens in foo()
below:
typedef struct { char x[100]; } chars;
chars make(void *p) {
printf("p = %p\n", p);
chars c;
return c;
}
void foo(void) {
chars b = make(&b);
}
如果允许,对它的使用是否有任何限制,例如,打印是否正常,我可以将其与另一个指针进行比较,等等吗?
If it is allowed, is there any restriction on its use, e.g., is printing it OK, can I compare it to another pointer, etc?
实际上,它似乎可以在我测试过的编译器上进行编译,并且大多数时候都具有预期的行为(但并非总是如此),但这远不能保证.
In practice it seems to compile on the compilers I tested, with the expected behavior most of the time (but not always), but that's far from a guarantee.
推荐答案
- Structure,union和枚举标签的作用域始于 声明标签的类型说明符中的标签.每个枚举常量的范围如下: 在其定义的枚举器出现在枚举器列表之后立即开始. 任何 其他标识符的范围仅在其声明符完成之后开始.
- Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.
在
chars b = make(&b);
// ^^
声明器是b
,因此它在其自己的初始化器中.
the declarator is b
, so it is in scope in its own initializer.
- 对于这样一个没有可变长度数组类型的[automatic]对象,其生存期将延长 从进入与之关联的块开始,直到该块的执行结束 任何方式.
- For such an [automatic] object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.
所以在
{ // X
chars b = make(&b);
}
b
的生存期始于X
,因此在初始化程序执行时,它既有效又在范围内.
the lifetime of b
starts at X
, so by the time the initializer executes, it is both alive and in scope.
据我所知,这实际上与
{
chars b;
b = make(&b);
}
没有理由在那儿不能使用&b
.
There's no reason you couldn't use &b
there.
这篇关于具有自动存储持续时间的变量的地址可以在其定义中使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!