我正在阅读有关默认初始化的 cppreference 页面,我注意到一个部分说明了以下内容:
//UB
int x;
int y = x;
//Defined and ok
unsigned char c;
unsigned char d = c;
Run Code Online (Sandbox Code Playgroud)
无符号字符的相同规则也适用于 std::byte 。
我的问题是,如果您在分配之前尝试使用该值(如上例),而不是 unsigned char,那么为什么所有其他非类变量(int、bool、char 等)都会导致 UB?为什么 unsigned char 很特别?
我试图用不同的整数填充数组,但它没有按预期工作。
#include <iostream>
using namespace std;
int main(){
int i=0;
int num;
int MyArray[]={};
while (true) {
cout<<"sayi giriniz"<<endl;
cin>>num;
MyArray[i]=num;
i++;
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
https://i.stack.imgur.com/NhCsE.jpg
当我输入第三个值时,它给出了意想不到的结果。