C 和 C++ 中的行为未定义
下面,我们将看到一些 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. 尝试使用未初始化变量。
示例代码
#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. 尝试访问空指针值。
示例代码
#include <iostream>
using namespace std;
int main() {
int *ptr = NULL;
cout << "The pointer value is: " << *ptr;
}输出
Runtime error for accessing null pointer values
4. 尝试访问空指针值。
示例代码
#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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP