2. 标签语句

标签语句(Labeled statements) 仅用于 goto 语句 或 switch 语句中。标签语句的特点是在执行的语句前都有一个英文冒号(:)结尾的标签,冒号前面就是标签。

标签语句的作用是用于程序中语句位置的定位。

标签语句的语法有三种

identifier : statement
case constant-expression : statement
default : statement

中文表示:

标识符 : 语句
case 常量表达式 : 语句
default : 语句

说明:

  1. 其中 casedefault 标签仅能出现在 switch 语句中。
  2. 常量表达式是指在编译阶段就能确定结果的表达式。此表达式的值在运行时不可修改。
  3. 标签的名字必须是标识符,且此标识符在当前函数中必须唯一。
  4. identifier : statement 的语法格式通常用于为 goto 语句定义跳转标签。

示例:

#include <stdio.h>

int main(int argc, char *argv[]) {
    int season;

    printf("请输入一年中的季度(1/2/3/4):");
    scanf("%d", &season);
    switch (season) {
        case 1:  // <--- 此处是标签语句
            printf("春季\n"); goto exit;
        case 2:  // <--- 此处是标签语句
            printf("夏季\n"); goto exit;
        case 3:  // <--- 此处是标签语句
            printf("秋季\n"); goto exit;
        case 4:  // <--- 此处是标签语句
            printf("冬季\n"); goto exit;
        default:  // <--- 此处是标签语句
            printf("您的输入有误!\n");
    }
    printf("判断结束\n"); // 正确输入时不会执行此语句;
exit:  // <--- 此处是标签语句
    printf("程序退出\n");

    return 0;
}