intfunc() { staticint state = 0, i = 0; switch (state) { case0: goto start; case1: goto label1; case2: goto label2; } start: state = 1; return0; label1: for (i = 0; i < 10; i++) { state = 2; return i; label2:; } return-1; }
intmain() { int x1 = func(); // 0 int x2 = func(); // 0 int x3 = func(); // 1 int x4 = func(); // 2 ... }
在 switch 中直接跳转:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
intfunc() { staticint state = 0, i = 0; switch (state) { case0: state = 1; return0; case1: for (i = 0; i < 10; i++) { state = 2; return i; case2:; } } return-1; }
这样手动地设置 state 就像在不停的使用 goto 语句一样,重复劳动的同时还容易写错,怎么自动设置 state?
使用 __LINE__
1 2 3 4 5 6 7 8 9 10 11
intfunc() { staticint state = 0, i = 0; switch (state) { case0: state = __LINE__; return1; case __LINE__: for (i = 0; i < 10; i++) { state = __LINE__; return i; case __LINE__:; } } return-1; }