Abo*_*msi 5 c c++ variables undefined-behavior language-lawyer
为什么以下编译没有错误?:
int main()
{
int x = x; //I thought this should cause an error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
标准中的哪个部分解释了为什么允许这样做?
这个问题在C中的答案与在C++中的答案略有不同.
在这两种情况下,都int x = x;尝试自己初始化x.
在C++中:[dcl.init]/12(N3936)表示对具有不确定值的对象的任何评估都会导致未定义的行为,除了涉及无符号的某些情况char.实际上有一个例子:
int f(bool b) {
unsigned char c;
unsigned char d = c; // OK, d has an indeterminate value
int e = d; // undefined behavior
return b ? d : 0; // undefined behavior if b is true
}
Run Code Online (Sandbox Code Playgroud)
在C:它更复杂.这是非常类似的行为,int b; foo(b - b);这是完全覆盖这里.
我不会重复那段文字,但结论是,在C11中:
int a = a; &a; 当且仅当系统具有陷阱表示时才会导致UB intint a = a;,没有后续发生&a,导致UB.历史记录:在C90中,这导致了UB.在C99 中引入了陷阱表示,并且在C11中引入了寄存器陷阱的可能性(对于Itanium).C++标准根本不涉及陷阱表示,在像位运算符产生负零的情况下似乎没有明确规定.
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |