Muliple goto statements in c

Hello,

I have a question about using multiple goto statements in the same function. I am reading some code and cannot follow the execution. I think it maybe my limited understanding of goto statements. If you have a function like so

Void afunction(){

if(x==1) { goto label1; } if(x==2){ goto label2; }

label1: //do something 1

label2: //do something 2

}

if I goto label1 will label2 also be executed?

Yup

renasis: Hello,

I have a question about using multiple goto statements in the same function. I am reading some code and cannot follow the execution. I think it maybe my limited understanding of goto statements. If you have a function like so

Void afunction(){

if(x==1) { goto label1; } if(x==2){ goto label2; }

label1: //do something 1

label2: //do something 2

}

if I goto label1 will label2 also be executed?

To answer your question - yes, label2 will also be executed.

But let me say this: Goto's are for experts only. Yes, they are simple - deceptively simple. So simple, that they are reviled by most accomplished coders. Yet so powerful, that they are revered as almost "god-sends" by experts. It is knowing when and where (and why) to use a goto that is the "devil in the details". I have seen some very interesting uses of goto (one was for a very interesting implementation of a state machine); I have also seen spaghetti code that would make your eyes bleed.

As an example of an acceptable use of goto in C, would be to escape a deeply nested set of if-then statements:

if (this) {
  if (that) {
      .
      30 levels of if-then deep...
      .
    if (anotherthing) {
      // do something here
      goto getmeouttahere;
    }
  }
}

getmeouttahere:

// more code, etc

Even such an example, though, should be avoided, if at all possible. Generally, if you are doing some kind of crazy set of massive nested if-then statements, there's a good chance you are either implementing your algorithm wrong, or you need to re-factor your code in some other kind of manner. There are other reasons and possibilities for using goto, many of them quite esoteric and rare. For most Arduino coding work, you will likely never run into these edge cases.

this format works well if you only want to do one thing, and not waste gobs of time evaluating tons of if (x ==){ } statements/

switch(x){ Case 1: // do 1 break; // jump the the ending } Case 2: // do 2 break; : case 99: // whatever is defined // do 99 break; } // end switch

Thanks for the replies! I will check out the code and see if I can understand it.