我正在阅读 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/