c++ - 无法理解 C 和 C++ 中静态的行为

标签 c++ c

#include <stdio.h>

int main()
{
    goto lb;
    static int a=5;

lb:
    goto b;
    int b=6;

b:
    printf("%d %d",a,b);
    return 0;
}

当我使用“.c”文件扩展名保存此代码时,它运行良好,输出为 5,后跟“垃圾”值。

但是,在 C++ 中,它会导致错误。我不明白为什么会出现错误。能告诉我怎么解决吗?

最佳答案

这与静态无关。您的问题可以用一段更小的代码来重现,其中根本没有 static 变量。

The compilation error is very clear :

main.cpp: In function 'int main()':
main.cpp:12:1: error: jump to label 'b' [-fpermissive]
 b:
 ^
main.cpp:9:10: error:   from here [-fpermissive]
     goto b;
          ^
main.cpp:10:9: error:   crosses initialization of 'int b'
     int b=6;
         ^

C++ 有禁止 goto 跨越初始化的规则;这与它对类和对象的支持密切相关,这些类和对象通常比您可以在 C 中创建的对象复杂得多。

您应该阅读this post .

关于c++ - 无法理解 C 和 C++ 中静态的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26426486/

相关文章:

c++ - 如何直接有效地访问非常大的文本文件?

python - 从 Python 调用 C 函数

c - 检测 C 头文件中的 undefined symbol

c++ - Adobe Eve ASL : how to render eve file into gui window?

C++ 将一组整数变量映射到值的有效方法

c - ATMEGA 328P 变频

c - 如何在c/汇编程序中通过cpuid指令识别cpu品牌名称

c++ - 将 make_iterator_range 与 std::string 一起使用

c++ - 使用 C++ 的 OpenCV 库 - 详细说明 cv::Mat::at 在大图像上导致 SIGSEGV

c++ - 如何将 istream * 转换为字符串或仅打印它?