C语言块作用域工作机制与标准解释的技术问询(含代码示例)
C语言块作用域工作机制与标准解释的技术问询(含代码示例)
哈喽~我来帮你捋清楚这个关于C语言块作用域的问题!先看你给出的这段示例代码:
#include <stdio.h> int main(void) { int n = 4; { n++; } printf("%d\n",n); return 0; }
这段代码运行后会输出5,原因很直接:内部的代码块并没有重新声明一个新的n变量,所以它直接访问的是外部main函数里声明的那个n,执行自增操作后,外部的n值就从4变成了5。
至于你问的C语言标准怎么解释这个机制——你提到的C17标准里的6.8条款第3点,其实已经给出了明确说明:
A block allows a set of declarations and statements to be grouped into one syntactic unit. Within a block, identifiers declared in an enclosing scope are visible unless a declaration in the block declares an identifier with the same name, in which case the outer declaration is hidden for the duration of the block.
简单来说,块的作用就是把一组声明和语句打包成一个语法单元;在内部块里,只要没有声明同名的标识符,外部作用域里的标识符就依然是可见的,内部代码可以直接访问和修改它。
备注:内容来源于stack exchange,提问作者ALICEZzz
相关产品推荐
相关产品推荐

