zoukankan      html  css  js  c++  java
  • a label can only be part of a statement and a declaration is not a statement” error

    The “a label can only be part of a statement and a declaration is not a statement” error occurs in C when it encounters a declaration immediately after a label.

    The C language standard only allows statements​ to follow a label. The language does not group declarations in the same category as statements.

    出错原因:C语言标准在标签后不允许存在变量定义语句。

    以下代码端会抛出此错误:

    #include<stdio.h>
    
    int main() {
      char * str1 = "hello";
      goto Here;
      
      Here:
      char * str2 = " world";
      printf("%s %s", str1, str2);
      return 0;
    }

    Note how str2 is declared immediately after the Here: label on line 88. The solution to this error​ is to add a semi-colon after the label. The compiler will translate it as a blank statement and ​not throw the error. The following code snippet implements this fix: 

    解决办法:在冒号后加分号

    #include<stdio.h>
    
    int main() {
      char * str1 = "hello";
      goto Here;
      
      Here: ; // 加分号semi-colon added after the label.
      char * str2 = " world";
      printf("%s %s", str1, str2);
      return 0;
    }

    The error can also occur when using switch statements in C, as ​the language treats cases similar to labels. Consider the following error scenario: 

    #include<stdio.h>
    
    int main() {
      char option = 'a';
      switch (option)
      {
        case 'a':
          char * str = "Case 'a' hit.";
          printf("%s", str);
          break;
      }
    }

    The solution is the same as before; a​ semi-colon needs to be added after the case 'a' statement on line 77. Alternatively, the entire case can be enclosed in curly braces to circumvent the error. The following code snippet implements both ways of fixing this error:

    • 分号(Semi-Colon)
    • 大括号(Curly-Braces)
    #include<stdio.h>
    
    int main() {
      char option = 'a';
      switch (option)
      {
        case 'a': ;
          char * str = "Case 'a' hit.";
          printf("%s", str);
          break;
      }
    }
  • 相关阅读:
    [C/C++] 结构体内存对齐用法
    [其他] 关于C语言中使用未声明函数的问题
    [其他] 项目中的一个小问题
    【C++】DLL内共享数据区在进程间共享数据(重要)
    [MFC] CString小用例
    [C++] 频谱图中 FFT快速傅里叶变换C++实现
    [MFC] TabControl选项卡的使用
    [MFC] CFile读写文件实现(高效)
    [MFC] 编辑框 EditControl 输入数字范围限制
    [MFC] 对话框菜单项Menu选中打勾(单选,多选)
  • 原文地址:https://www.cnblogs.com/jopny/p/14512349.html
Copyright © 2011-2022 走看看