
在这里,我们将看到一些C和C++代码,并尝试猜测结果。这些代码将生成一些运行时错误。
1. 除以零的错误是未定义的。
#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
2. Trying to use uninitialized variable.
#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)
3. Trying to access null pointer values.
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
using namespace std;
int main() {
int *ptr = NULL;
cout << "The pointer value is: " << *ptr;
}Runtime error for accessing null pointer values
4. Trying to access 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
5. 超出有符号整数的限制。
#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
6. 尝试更改字符串字面值中的某些字符。
#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.
以上就是在C和C++中的未定义行为的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号