如何访问外部块变量在内部块内的时候有块相同的变量声明? [英] How to access outer block variable in inner block when inner block have same variable declaration?
问题描述
int main(int argc, char** argv) {
int i=5;
{
int i=7;
printf("%d\n", i);
}
return 0;
}
如果我想访问外 I
( INT I = 5
)的价值printf的
那么就可以怎么做的?
If I want to access outer i
(int i=5
) value in printf
then how it can done?
推荐答案
C99标准的相关部分,第6.2.1节(鉴定网络连接器的作用域):
The relevant part of the C99 standard, section 6.2.1 (Scopes of identifiers):
的 4 的[...]如果一个标识符指定在同一名称空间两个不同的实体,该范围可能会重叠。如果是这样,一个实体(内部范围)的范围将是其他实体的范围(外部范围)的严格的子集。在内部范围内,该标识符指定的范围内声明的实体;在外部范围声明的实体被隐藏(不可见)内范围之内。
4 [...] If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will be a strict subset of the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.
要prevent <一个href=\"http://stackoverflow.com/questions/3882621/how-to-access-outer-block-variable-in-inner-block-when-inner-block-have-same-vari/3884427#3884427\">pmg's从消失回答:您可以通过隐藏之前宣布指向它的指针访问外部块变量发生:
Update
To prevent pmg's answer from disappearing: You can access the outer block variable by declaring a pointer to it before the hiding occurs:
int i = 5;
{
int *p = &i;
int i = 7;
printf("%d\n", *p); /* prints "5" */
}
当然给这样的隐藏变量是从来不需要总是不好的风格。
Of course giving hiding variables like this is never needed and always bad style.
这篇关于如何访问外部块变量在内部块内的时候有块相同的变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!