控制语句

goto

预计阅读时间2 分钟 5 views

goto 语句用于将程序控制权转移到代码中的其他部分。使用 goto 语句时,可以直接跳转到程序中的某个标签 (label)。标签是一个标识符,表示跳转的目标位置。

goto 语句的语法

goto label;
... 
...
label:
  ...
  ...

在上面的例子中,当 goto label; 被执行时,程序控制权会跳转到 label: 所在的位置,之后的代码将继续执行。


示例 1: 使用 goto 语句的例子

using System;

namespace CSharpGoto {

  class Program {
    public static void Main(string[] args) {

      // label
      repeat: 
        Console.WriteLine("Enter a number less than 10");
        int num = Convert.ToInt32(Console.ReadLine());  

        if(num >= 10) {
          // transfers control to repeat
          goto repeat;
        }

        Console.WriteLine(num + " is less than 10");
        Console.ReadLine();
    }
  }
}

输出:

Enter a number less than 10
99
Enter a number less than 10
9
9 is less than 10

工作机制

在这个示例中,goto 语句被放置在 if 语句内部。用户被提示输入一个小于 10 的数字。如果用户输入的数字大于或等于 10,goto repeat; 会将程序控制权转移到 repeat: 标签处,从而重新提示用户输入数字。这个过程会一直持续,直到用户输入的数字小于 10。


示例 2: gotoswitch 语句

在 C# 中,可以使用 gotoswitch 语句配合,将程序控制权转移到特定的 case。例如:

using System;

namespace CSharpGoto {

  class Program {

    public static void Main(string[] args) {

      Console.Write("Choose your coffee? milk or black: ");
      string coffeeType = Console.ReadLine();

      switch (coffeeType) {
        case "milk":
          Console.WriteLine("Can I have a milk coffee?");
          break;

        case "black":
          Console.WriteLine("Can I have a black coffee?");
          // transfer code to case "milk" 
          goto case "milk";

        default:
          Console.WriteLine("Not available.");
          break;
      }
      Console.ReadLine();
    }
  }
}

输出:

Can I have a black coffee?
Can I have a milk coffee?

工作机制

在这个程序中,用户输入的咖啡类型是 “black”。当 switch 语句执行到 case "black" 时,程序打印 “Can I have a black coffee?”。随后,goto case "milk"; 将程序控制权转移到 case "milk",于是 “Can I have a milk coffee?” 也被打印出来。


示例 3: 使用 goto 跳出 for 循环

在 C# 中,还可以使用 goto 从循环中跳出。例如:

using System;

namespace CSharpGoto {

  class Program {

    static void Main() {
      for(int i = 0; i <= 10; i++) {

        if(i == 5) {
          // transfers control to End label
          goto End;
        }

        Console.WriteLine(i);
      }

      // End label
      End:
        Console.WriteLine("Loop End");
        Console.ReadLine();
    }
  }
}

输出:

0
1
2
3
4
Loop End

工作机制

在这个程序中,for 循环的初始条件是从 0 到 10 进行迭代。每当 i 的值等于 5 时,goto End; 语句会将程序控制权转移到 End: 标签处,从而跳出循环,直接执行循环后的语句并打印 “Loop End”。


总结

  • goto 语句是一种控制转移语句,允许程序跳转到指定的标签位置。
  • 它可以与 if 语句、switch 语句、循环等结构结合使用,实现复杂的控制流。
  • 尽管 goto 语句有其用途,但应谨慎使用,因为它可能导致代码难以维护和理解。

Leave a Comment

分享此文档

goto

或复制链接

内容