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