当您阅读答案时,您可能会知道问题的答案 -这是语法,您无法避免。但我会更进一步,解释为什么会这样?
当您为任何语言设计编译器时,您必须处理scope 和变量的生命周期。像
在C
int p=2015;
int foo()
{ ~~~~~~~~~~~~~~~~~~~~~~~>
int p=2014; |
printf("\n %d ",p); | This is the local scope
return p; |
} ~~~~~~~~~~~~~~~~~~~~~~~>
输出:2014 年
现在按照规则,我们总是在局部范围内寻找变量,然后逐渐向外范围。
总而言之,您必须了解应该在哪里打开新范围。这就是'{'大括号的作用。我们可以说,当编译器看到一个“{”时,显然一个作用域开始了,当它遇到一个“}”时它结束了。这将帮助我们存储和操作标识符(嗯 :-) 它是我们这样做的符号表)。
现在,如果标准支持您所说的内容会发生什么--
:-( 前面的问题
int x=100;
int y=200;
int foo(int x)
return x+y;-~~~~~~~~~~~> which x :-( the one that I have got as a parameter or the global one.
int main()
{
int x=2;
printf("%d\n",foo(x));
}
所以这就是问题所在。希望这会有所帮助。
如果你用正确的语法运行它
int foo(int x)
{
return x+y;
}
答案将是..哦!你运行它!这个想法会很清楚。
C 语法的一部分(Courtesy-Lysator)
function_definition
: declaration_specifiers declarator declaration_list compound_statement
| declaration_specifiers declarator compound_statement
| declarator declaration_list compound_statement
| declarator compound_statement
compound_statement
: '{' '}'
| '{' statement_list '}'
| '{' declaration_list '}'
| '{' declaration_list statement_list '}'
;