きままにブログ

プログラミングを主とした私のメモ帳です。寂しいのでコメントください笑

gotoかわいいよgoto

C/C++ではgotoが使える。とても自由なこの制御構文は、2重のforループを抜けるとき大変役立つ。

#include <iostream>

using namespace std;

void func() {
	cout << "In func()" << endl;
	goto exit;
	cout << "skip" << endl;
exit:
	cout << "End of func()" << endl;
}

int main() {
	for(int i = 0; i < 3; ++i) {
		for(int j = 0; j < 3; ++j) {
			if(i + j == 4) {
				goto exit;
			}
			cout << "j-end" << endl;
		}

		cout << "i-end" << endl;
	}
exit:
	cout << "loop-end" << endl;
	func();

	cin.get();
	return 0;
}

でも

#include <iostream>

using namespace std;

int main() {
	goto label;

	int x = 10;

label:
	cin.get();
	return 0;
}

のようにgotoの間に宣言 & 初期化してはならないらしい。