在 if 条件中声明变量且没有大括号时出现编译器错误 [英] Compiler error when declaring a variable inside if condition and no curly braces

查看:23
本文介绍了在 if 条件中声明变量且没有大括号时出现编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第一个 if 编译良好而第二个失败?

Why does this first if compile well and the second fail?

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

推荐答案

因为语言规范是这样说的:

Because the language spec says so:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html

声明将实体引入程序并包含一个标识符(第 3.8 节),可在名称中使用该标识符来引用该实体.声明的实体是以下之一:
...
局部变量,以下之一:
* 在块中声明的局部变量(第 14.4 节)
* 在 for 语句中声明的局部变量(第 14.14 节)

A declaration introduces an entity into a program and includes an identifier (§3.8) that can be used in a name to refer to this entity. A declared entity is one of the following:
...
A local variable, one of the following:
* A local variable declared in a block (§14.4)
* A local variable declared in a for statement (§14.14)

您的第一个示例是在块内声明 i(用花括号表示).你的第二个不是,也不是 for 语句.

Your first example is declaring i inside a block (denoted by curly braces). Your second isn't, nor is it a for statement.

编辑添加:这只是常识.如果允许,那就没用了.它会立即超出范围.

Edited to add: Which just makes commons sense. If it were allowed, it would be useless. It would immediately fall out of scope.

这篇关于在 if 条件中声明变量且没有大括号时出现编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆