在if条件中声明变量且没有大括号时出现编译器错误

为什么第一个if编译正确,而第二个编译失败?


if(proceed) {int i;} // This compiles fine.

if(proceed) int i;// This gives an error. (Syntax error on token ")", { expected after this token)


子衿沉夜
浏览 753回答 3
3回答

慕容森

来自Java语言规范。    区块:            { BlockStatements opt }    BlockStatements:             BlockStatement             BlockStatements  BlockStatement    BlockStatement:             LocalVariableDeclarationStatement             ClassDeclaration             语句和    IfThen声明:            if(表达式)语句似乎int i是一个LocalVariableDeclarationStatement,而不是一个Statement。因此它不起作用。

慕桂英4014372

这是因为它不是有用的代码。如果您有一个不带大括号({})的if语句,则仅执行if之后的第一行/语句。因此,如果仅声明局部变量,则不能在其他任何地方使用它。因此,声明它绝对是多余的。if(proceed){int i= 0; // variable i can be used here//...}if (proceed) int i; // i can not be used anywhere as it is a local variable
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java