C ++程序员应该知道哪些常见的未定义行为?
在C++中,存在一些未定义的行为。这些是通过在C++中执行一些任务来识别的。没有这样的直接定义。所有要使用C++达到不同目的的程序员都应该知道这几件事。
在这里,我们将看到一些C++代码。并尝试猜测结果。该代码将生成一些运行时错误。
除零错误未定义。
范例程式码
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 0;
int z = x / y;
cout << "Done" << endl;
}输出结果
Runtime error for divide by zero operation
尝试使用未初始化的变量。
范例程式码
#include <iostream>
using namespace std;
int main() {
bool x;
if(x == true)
cout << "true value";
else
cout << "false value";
}输出结果
false value (This may differ in different compilers)
尝试访问空指针值。
范例程式码
#include <iostream>
using namespace std;
int main() {
int *ptr = NULL;
cout << "The pointer value is: " << *ptr;
}输出结果
Runtime error for accessing null pointer values
尝试访问空指针值。
范例程式码
#include <iostream>
using namespace std;
int main() {
int array[10];
for(int i = 0; i<=10; i++) {
cout << array[i] << endl;
}
}输出结果
Runtime error for accessing item out of bound. Some compiler may return some arbitrary value, not return any error Going beyond limit of signed int.
范例程式码
#include <iostream>
using namespace std;
int main() {
int x = INT_MAX;
cout << "x + 1: " << x + 1;
}输出结果
x + 1: -2147483648 circulate to the minimum number of signed int
尝试更改String文字中的某些字符。
范例程式码
#include <iostream>
using namespace std;
int main() {
char *str = "Hello World";
str[2] = 'x';
cout << str;
}输出结果
Runtime error because we are trying to change the value of some constant variables.
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短