开发者

Jumping to a specific line in code using C

开发者 https://www.devze.com 2023-04-04 05:00 出处:网络
Sorry if this question is silly, but I can\'t seem to find the answer on Google. I haven\'t done C programing in a while and for the life of me remember how, in C or C++, to jump back (or forward) to

Sorry if this question is silly, but I can't seem to find the answer on Google. I haven't done C programing in a while and for the life of me remember how, in C or C++, to jump back (or forward) to a specific line in code. If I remembe开发者_开发问答r right, there was a way to do this.

Thanks for the help!

Cheers!


The infamous goto, in conjuntion with labels.

label_name:
goto label_name;

Before using it, search for 'goto considered harmful'.


C and C++ do not have a concept of 'lines' after the preprocessing stage. As such, you cannot 'jump' to a line of code.

If you want to jump to a line of code in your editor, this depends on what editor you are using. If you want to jump to a specific statement (not line) at runtime, you could use goto, but this should be avoided for most circumstances, as it leads to difficult to understand code, and other control-flow structures are more appropriate in most cases.


If you want the nasty and easy solution: goto and then a label which indicates the line of code you want to go to.

Normally though, you'd have a function with the specific functionality you want to invoke, and call that function.


Use a goto statement, like this:

goto SomeLine;

// Code code code...

SomeLine:

Note that this is considered extremely bad practice. Chances are, there's a better way to organize your code that avoids the need altogether.


I do also think that the goto instruction should not be used when you can help it.

However, contrary to many other languages, there isn't a neat way to exit from multi-layered if() blocks and the easiest is to the goto in this case.

What I suggest is that you add comments and use wisely named labels (l1: ... goto l1; sucks.)

Note that people will tell you that the goto is bad, and use the break and continue statements in loops like crazy. They have the exact same side effect as the goto instruction and could be considered as bad (but aren't).


There are some options to do it: 'goto' instruction, setjmp/longjmp functions. Also you can use in c++ SEH (exception propagation and handling), but it isn't simple. And if you really nead such thing as jumping to particular line of code, I will recommend you to rewrite your code using loops and conditionals with additional state variables. Because you have serious problem with structure or design of your code. It may look ugly but it is more safer than using goto and other "black magic"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号