C/C++: goto into the for loop

前端 未结 7 1599
一向
一向 2021-02-13 21:14

I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this c

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 21:33

    Yes, that's legal.

    What you're doing is nowhere near as ugly as e.g. Duff's Device, which also is standard-compliant.

    As @Alexandre says, don't use goto to skip over variable declarations with non-trivial constructors.


    I'm sure you're not expecting local variables to be preserved across calls, since automatic variable lifetime is so fundamental. If you need some state to be preserved, functors (function objects) would be a good choice (in C++). C++0x lambda syntax makes them even easier to build. In C you'll have no choice but to store state into some state block passed in by pointer by the caller.

提交回复
热议问题