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
试图更改字符串文本中的某些字符。
示例代码
#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.
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP