c++ - 为什么goto这个宏定义会导致程序崩溃?

标签 c++ c macros goto

我正在阅读 post , 在其中一个答案中有以下代码

#define goto { int x = *(int *)0; } goto

作者说每次有人尝试使用 goto 语句时,他的程序都会崩溃,我的问题是为什么?按照我的理解,int x = *(int *)0;将内存地址的前4个字节中的whatever内容赋值给了x,但是为什么这样会肯定会使程序崩溃?

最佳答案

只是因为您正在取消引用 NULL 指针。但是程序会崩溃是没有定义的。它可能会崩溃,可能不会崩溃或做一些奇怪的事情。这只是一种未定义的行为,最好避免。

值得注意的是 goto 并不是那么无用。每个关键字都有自己的位置,语言作者和标准委员会成员有理由继续维护它(考虑到语言正在发生一些巨大的变化)。如果使用得当,goto 在 C 和 C++ 中占有一席之地。

Just to give an idea how this is an UB, using VC11, I compiled the above snippet in debug and release mode. In debug mode it crashed but in release mode, compiler simply optimized out the statement and there was no crash.

关于c++ - 为什么goto这个宏定义会导致程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29722514/

相关文章:

c++ - cinder函数过载错误

c++ - 任何 C++ 98 标准容器操作都可以抛出 std::bad_alloc 吗?

c - glut 中的定时器功能

c - 奇怪的宏结构

c++ - 重新加载内联 ostringstream 宏

c++ - 从用于 boost deadline_timer 的处理程序访问类数据

c# - C 风格语言中匿名 { } block 的目的是什么?

c++ - 错误 C2440 : '=' : cannot convert from 'int' to 'char [5]'

c - 在 Assembly Works 中如何调用带有大量参数的函数

ruby-on-rails - 如何编写一个 RSpec Controller 宏,它可以接受由 let 或在 before block 中定义的参数?