Question

Is there any alternative for goto statement in c programming.

Actually i am planning to make one new simulator for my application. For this simulator i need to go particular place again and again inside main from some other function. Goto only works with in the functions otherwise it won't work. Can any one suggest me any other alternative methods.

Thanks advance.

Was it helpful?

Solution

Separate your main into functions. Instead of jumping to a location inside main, execute an appropriate function. That might require passing some parameters to the functions but it surely worth it.

OTHER TIPS

You can use your own functions and call it whenever you need it.

Put "the place you need to go to" inside a function and call that function every time you need.

Of course that function will have its own scope and can't access variables from the calling point.

So you'll need to pass the required data to the function or make use (discouraged) of globals

For this simulator i need to go particular place again and again inside main from some other function.

This can quickly lead to spaghetti code. goto within a function to jump forward, for example into cleanup code, has it's fair uses. Jumping between functions: Don't do this, this is horrible (technically it can be done with some helpers which I'm not going to name here, to keep the temptation from you).

So what you try to do sounds a lot like so called coroutines to me. And that can be done with C, by utilizing some construct called "Duff's Device". There's a nice article about it here: http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html

And then there's a C coroutine library on Google Code: https://code.google.com/p/libconcurrency/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top