Goto instruction in C #

I am writing a function, as in C #:

public void CountNumber() 
{
       for(int i = 0; i < 40; i++) {
          if(i > 20) {
               goto out1;
          }

          Console.WriteLine("hello " + 1);

          out1:
             string hello = "";
       }
}

This basically counts the number, and if I'm over 20, it should not write to console.writeline. it must step over and press "out1", but "out1" must have a function at the end to compile. It must have the command "string hello =" "to compile. I do not need the string hello =" "". I just want him to do nothing and get the end of the cycle. Is there a way to do this without the "string hello =" "" that the out1 instruction requires? How:

public void CountNumber() 
{
       for(int i = 0; i < 40; i++) {
          if(i > 20) {
               goto out1;
          }

          Console.WriteLine("hello " + 1);

          out1:
       }
}

Thank.

+5
source share
6 answers

: while i<=20 i<40 ( ) Console.WriteLine if if.

, "" . , goto continue, :

public void CountNumber() 
{
   for(int i = 0; i < 40; i++) {
      if(i > 20) {
         continue; // Skips the rest of this loop iteration
      }

      Console.WriteLine("hello " + 1);
   }
}

, break, , .

+17

, , goto, , .

. , . , .

    out1:
    ;
} 

    out1:
    {}
}

, , , , .

+26

- if...else . , , for, 20.

   for(int i = 0; i < 40; i++) 
   {
      if(i <= 20) 
      {
          Console.WriteLine("hello " + 1);
      }
      //other code
   }
+10

goto- , :

  • continue .
  • break
  • return

You should only consider gotoif none of the above actions do what you want. And in my experience this very rarely happens.

Sounds like you want to use it continuehere.

+5
source

To do this, you can use the keyword continue:

public void CountNumber()  {
  for(int i = 0; i < 40; i++) {
    if(i > 20) {
      continue;
    }
    Console.WriteLine("hello " + 1);
  }
}

However, consider instead if:

public void CountNumber()  {
  for(int i = 0; i < 40; i++) {
    if(i <= 20) {
      Console.WriteLine("hello " + 1);
    }
  }
}
+4
source
public void CountNumber() 
{
       for(int i = 0; i < 40; i++) {
          if(i > 20) {
              continue;
          }

          Console.WriteLine("hello " + 1);

       }
}
+1
source

All Articles