c++ – C ++ Questions about the Goto statement


Studying programming I came across this strange instruction, in a way I understand that it jumps to the instruction it points to, but why isn't it used? The truth is a curious alternative to loops and conditionals but I have read that it is not good to use it, and my doubts are:

  • Why is it not used?

  • What happens in the program when it is used?


Why is it not used?

By the obfuscation of the code that it implies.

For example, in a loop ( do , while , for ), we can be sure that the only way out is in the loop itself; Either why the necessary condition was met, or why we use a break .

We can therefore check the code back, knowing that to arrive at an exact point, necessarily has gone through the above (taking into account the if( ) ... else ... , of course).

This is not true in a goto . If we find a label, a destination for a goto , there is no way of knowing the sequence of instructions that got us there. Where we come from ? Above all, if we make our code a sample of goto .

What happens in the program when it is used?

Exactly what you expect: you jump to the indicated tag. There are no major side effects, or anything bad involved in using it, except as indicated in the previous paragraph. If you are in a block { ... } , the local variables to the block cease to exist and, if you are in C ++, the destructors are called correctly; everything works as expected.

Scroll to Top