EzDev.org

goto

Linux Shell 'cd' replacement tool. cd on steroids, with fuzzy file finder and a directory bookmark saver.


The equivalent of a GOTO in python [duplicate]

This question already has an answer here:

I am self teaching myself python 2.7. I have some experience in using BATCH, which has a GOTO statement. How do I do that in python? For example, suppose I want to jump from line 5 to line 18.

I realize there have been previous questions regarding this topic, but I have not found them sufficiently informative or, are too high level in python for my current understanding.


Source: (StackOverflow)

How do I get GDB to break out of a loop?

I can tell GDB to return from a function immediately with return, and call a function with call myFunction.

But how do I get it break out of the current loop? i.e. to act as if it's hit a break; statement.

Is jump myfile.c:<linenumber> the way to do this?


Source: (StackOverflow)

Other ways to deal with "loop initialization" in C#

To start with I'll say that I agree that goto statements are largely made irrelevant by higher level constructs in modern programming languages and shouldn't be used when a suitable substitute is available.

I was re-reading an original edition of Steve McConnell's Code Complete recently and had forgotten about his suggestion for a common coding problem. I had read it years ago when I was first getting started and don't think I realized how useful the recipe would be. The coding problem is the following: when executing a loop you often need to execute part of the loop to initialize state and then execute the loop with some other logic and ending each loop with the same initialization logic. A concrete example is implementing String.Join(delimiter, array) method.

I think everybody's first take on the problem is this. Assume the append method is defined to add the argument to your return value.

bool isFirst = true;
foreach (var element in array)
{
  if (!isFirst)
  {
     append(delimiter);
  }
  else
  {
    isFirst = false;
  }

  append(element);
}

Note: A slight optimization to this is to remove the else and put it at the end of the loop. An assignment usually being a single instruction and equivalent to an else and decreases the number of basic blocks by 1 and increases the basic block size of the main part. The result being that execute a condition in each loop to determine if you should add the delimiter or not.

I've also seen and used other takes on dealing with this common loop problem. You can execute the initial element code first outside the loop, then perform your loop from the second element to the end. You can also change the logic to always append the element then the delimiter and once the loop is completed you can simply remove the last delimiter you added.

The latter solution tends to be the one that I prefer only because it doesn't duplicate any code. If the logic of the initialization sequence ever changes, you don't have to remember to fix it in two places. It does however require extra "work" to do something and then undo it, causing at least extra cpu cycles and in many cases such as our String.Join example requires extra memory as well.

I was excited then to read this construct

var enumerator = array.GetEnumerator();
if (enumerator.MoveNext())
{
  goto start;
  do {
    append(delimiter);

  start:
    append(enumerator.Current);
  } while (enumerator.MoveNext());
}

The benefit here being that you get no duplicated code and you get no additional work. You start your loop half way into the execution of your first loop and that is your initialization. You are limited to simulating other loops with the do while construct but the translation is easy and reading it is not difficult.

So, now the question. I happily went to try adding this to some code I was working on and found it didn't work. Works great in C, C++, Basic but it turns out in C# you can't jump to a label inside a different lexical scope that is not a parent scope. I was very disappointed. So I was left wondering, what is the best way to deal with this very common coding problem (I see it mostly in string generation) in C#?

To perhaps be more specific with requirements:

  • Don't duplicate code
  • Don't do unnecessary work
  • Don't be more than 2 or 3 times slower than other code
  • Be readable

I think readability is the only thing that might arguably suffer with the recipe I stated. However it doesn't work in C# so what's the next best thing?

* Edit * I changed my performance criteria because of some of the discussion. Performance is generally not a limiting factor here, so the goal more correctly should be to not be unreasonable, not to be the fastest ever.

The reason I dislike the alternate implementations I suggest is because they either duplicate code which leaves room for changing one part and not the other or for the one I generally choose it requires "undoing" the operation which requires extra thought and time to undo the thing that you just did. With string manipulation in particular this usually leaves you open for off by one errors or failing to account for an empty array and trying to undo something that didn't happen.


Source: (StackOverflow)

Continue Considered Harmful? [closed]

Should developers avoid using continue in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about Goto?


Source: (StackOverflow)

GOTO before local variable

Does the following piece of code constitute undefined behaviour, since I am jumping before the variable declaration and using it via a pointer? If so, are there differences between the standards?

int main() {
  int *p = 0;
label1: 
  if (p) {
    printf("%d\n", *p);
    return 0;
  }
  int i = 999;
  p = &i;
  goto label1;
  return -1;
}

Source: (StackOverflow)

Why do some kernel programmers use goto instead of simple while loops?

When I learned C, teacher told me all day long: "Don't use goto, that's a bad habit, it's ugly, it's dangerous!" and so on.

Why then, do some kernel programmers use goto, for example in this function, where it could be replaced with a simple

while(condition) {} 

or

do {} while(condition);

I can't understand that. Is it better in some cases to use goto instead of while/do-while? And if so, why?


Source: (StackOverflow)

Elegant way for exiting a function neatly without using goto in C

We often write some functions which have more than one exit point (that is, return in C). At the same time, when exiting the function, for some general works such as resource cleanup, we wish to implement them only once, rather than implementing them at every exit point. Typically, we may achieve our wish by using goto like the following:

void f()
{
    ...
    ...{..{... if(exit_cond) goto f_exit; }..}..
    ...
    f_exit:
    some general work such as cleanup
}

I think using goto here is acceptable, and I know many people agree on using goto here. Just out of curiosity, does there exist any elegant way for neatly exiting a function without using goto in C?


Source: (StackOverflow)

Use a 'goto' in a switch?

I've seen a suggested coding standard that reads Never use goto unless in a switch statement fall-through.

I don't follow. What exactly would this 'exception' case look like, that justifies a goto?


Source: (StackOverflow)

Get out of multiple loops? [duplicate]

Possible Duplicate:
Breaking out of a nested loop

I have this code

foreach (___)
{
    foreach (___)
    {
        foreach (___)
        {
            if (condition)
            {
                //break out of all loops
            }
        }
    }
}

But break only "breaks" the most inner loop (sorry for my english) and I want to leave them all...

I was thinking about :

  1. GOTO, but I've always been told to not use it
  2. A sort of boolean-flag

Is there any more elegant way ? like provided by C# ?

Thanks in advance for any help !


Source: (StackOverflow)

Goto out of a block: do destructors get called?

Consider the following code:

void foo()
{
    {
        CSomeClass bar;

        // Some code here...

        goto label;

        // and here...
    }

label:
    // and here...
}

Will the destructor of bar be called ?


Source: (StackOverflow)

`goto` in Python

I must use goto in Python. I read this but my Python implementation (CPython 2.7.1 on Mac) does not have this module, so it doesn't seem to be portable. It should at least work in all Python implementations which support CPython bytecode (esp. I care about CPython and PyPy).

I could go and build up the bytecode manually (i.e. write my own Python compiler) because there is such an instruction (JUMP_ABSOLUTE and friends). But I wonder if there is an easier way. Is it possible via inspect or so to call a single bytecode instruction? I also thought about compiling via Python and then automatically patching the generated Python bytecode.


Of course, people will ask why and will not give me any helpful answer if I don't explain why I really really need this. So in short my use case: I am translating a C AST to Python AST and compiling this. I can map every logical flow (all the loops and other stuff) in some way to equivalent Python code. Everything except goto. Related projects: PyCParser (see interpreter.py), PyCPython, PyLua.


Source: (StackOverflow)

Is it possible to store the address of a label in a variable and use goto to jump to it?

I know everyone hates gotos. In my code, for reasons I have considered and am comfortable with, they provide an effective solution (ie I'm not looking for "don't do that" as an answer, I understand your reservations, and understand why I am using them anyway).

So far they have been fantastic, but I want to expand the functionality in such a way that requires me to essentially be able to store pointers to the labels, then go to them later.

If this code worked, it would represent the type of functionality that I need. But it doesn't work, and 30 min of googling hasn't revealed anything. Does anyone have any ideas?

int main (void)
{
  int i=1;
  void* the_label_pointer;

  the_label:

  the_label_pointer = &the_label;

  if( i-- )
    goto *the_label_pointer;

  return 0;
}

Source: (StackOverflow)

Design pattern that can replace chained switch/goto?

I have a code for updating my application resources to current application version. This code is called after application update.

int version = 1002;   // current app version

switch(version)
{
   case 1001:
      updateTo1002();
      goto case 1002;

   case 1002:
      updateTo1003();
      goto case 1003;

   case 1003:
      updateTo1004();
      goto case 1004;
      break;

   case 1004:
      updateTo1005();
      break;
}

Here we have a cascade method calling by jumping to specified case block. I wonder - is that good practice to use go to (often considered as such bad practise!) in this case? I do not want to call method one by other - like this:

updateTo1002()
{
   // do the job
   updateTo1003();
}
updateTo1003()
{
   // do the job
   updateTo1004();
}

It there any design pattern describes such an issue?


Source: (StackOverflow)

Is there ever a reason to use goto in modern .NET code?

I just found this code in reflector in the .NET base libraries...

    if (this._PasswordStrengthRegularExpression != null)
    {
        this._PasswordStrengthRegularExpression = this._PasswordStrengthRegularExpression.Trim();
        if (this._PasswordStrengthRegularExpression.Length == 0)
        {
            goto Label_016C;
        }
        try
        {
            new Regex(this._PasswordStrengthRegularExpression);
            goto Label_016C;
        }
        catch (ArgumentException exception)
        {
            throw new ProviderException(exception.Message, exception);
        }
    }
    this._PasswordStrengthRegularExpression = string.Empty;
Label_016C:
    ... //Other stuff

I've heard all of the "thou shalt not use goto on fear of exile to hell for eternity" spiel. I always held MS coders in fairly high regard and while I may not have agreed with all of their decisions, I always respected their reasoning.

So - is there a good reason for code like this that I'm missing? Was this code extract just put together by an inept developer? or is .NET reflector returning inaccurate code?

I'm hoping there is a good reason, and I'm just blindly missing it.

Thanks for everyone's input


Source: (StackOverflow)

To Use GOTO or Not?

Currently I am working on a project where goto statements are heavely used. The main purpose of goto statements is to have one cleanup section in routine rather than multiple return statements. Like below

BOOL foo()
{
   BOOL bRetVal = FALSE;
   int *p=NULL;

   p = new int;
   if(p==NULL)
   {
     cout<<" OOM \n";
     goto Exit;
   }

   // Lot of code...
Exit:
   if(p)
   {
     delete p;
     p= NULL;
   }
   return bRetVal;
}

This makes much easier as we can track our clean up code at one section in code.ie after Exit label.

However I have read many places its bad practice to have goto statements.

Currently I am reading Code Complete book and it says that we need to use variable close to their declarations. If we use goto then we need to declare/initialize all variables before first use of goto otherwise compiler give errors that initialization of xx variable is skipped by goto statement.

I am not sure which way is right. any thoughts???


From Scott's comment It looks like using goto to jump from one section to another is bad as it make the code hard to read and understand.

But if we use goto just to go forward and to one label then it should be fine???


Source: (StackOverflow)