java - 单行函数是否需要大括号?

标签 java c# c++ c coding-style

我知道单行 block 不需要花括号,例如 if 语句等,但是单行函数需要花括号吗?

例如:

public int foo(int bar) 
    return bar;

public int foo(int bar) 
{
    return bar;
}

这两个都同样有效,还是第一个例子不是?

我正在寻找与 C 系列和类似语言(C、C++、C#、Java 等)相关的答案。

最佳答案

当您阅读答案时,您可能会知道问题的答案 - 这是语法,您无法避免。但我会更进一步解释一下为什么会这样?

当您为任何语言设计编译器时,您必须处理变量的范围和生命周期。喜欢 在C中

int p=2015;
int foo()
{ ~~~~~~~~~~~~~~~~~~~~~~~>
    int p=2014;          |
    printf("\n %d ",p);  |  This is the local scope 
    return p;            |
} ~~~~~~~~~~~~~~~~~~~~~~~>

Output: 2014

现在,根据规则,我们总是在本地范围内查找变量,然后逐渐向外部范围查找。

So in a word you have to understand where new scope should be opened. That's what the '{' braces does. We can say that when compiler sees a '{' then obviously a scope begins and it ends when it encounter a '}'. This will help us store and manipulate the identifiers (well :-) it is symbol table throuh which we do this).

现在如果标准支持你所说的东西会发生什么-- :-( 前面的问题

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 语法的一部分(由 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 '}'
    ;

关于java - 单行函数是否需要大括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29626239/

相关文章:

java - 使用 Jena 将子子项添加到 RDF

c# - 如何在 MVC 中编写包含 FormsAuthenticationTicket 的单元测试用例

c++ - C++中的空指针是什么?

c++ - 返回函数开头的方法

c++ - 选择成员函数而不是成员函数定义中具有相同名称的函数

java - 遍历 ArrayList 并返回满足 instanceof 检查的对象的 ArrayList

私有(private)方法上的 Javax 验证不会被触发

java - 如何在另一个客户端项目中调用@Remote EJB

c# - SelectListItem 文本未显示

c# - 如何利用 C# 属性和反射在标记对象上注入(inject)/强制后期绑定(bind)?