7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

for文中でreturnしてはならない

Last updated at Posted at 2017-10-25

for文の中にreturnを書くと、1回しか回らない。
下のサンプルコードの
for (; ;)
は無限ループのはずだが、
returnでループが打ち切られて即終了となる。

まともなコードを書くのであれば、
returnはforの外に書く必要がある。

public class ForReturn {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		String result = forReturn(2);
		System.out.println(result);
	}

	public static String forReturn(int i){
		for (; ;){
		return "不合格";
		}
	}
}
実行結果
不合格

ということを今更になって学んだ今日でした。。。。。

7
3
11

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?