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