ใน C ++ มีพฤติกรรมที่ไม่ได้กำหนดบางอย่าง สิ่งเหล่านี้ถูกระบุโดยการทำงานบางอย่างใน C ++ ไม่มีคำจำกัดความโดยตรงดังกล่าว โปรแกรมเมอร์ทุกคนควรทราบบางสิ่งเหล่านี้ ซึ่งต้องการใช้ C++ เพื่อวัตถุประสงค์ที่แตกต่างกัน
ที่นี่เราจะเห็นรหัส C ++ และลองเดาผลลัพธ์ รหัสจะทำให้เกิดข้อผิดพลาดรันไทม์
ข้อผิดพลาด Divide By Zero ไม่ได้กำหนดไว้
โค้ดตัวอย่าง
#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)
กำลังพยายามเข้าถึงค่าตัวชี้ null
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int *ptr = NULL;
cout << "The pointer value is: " << *ptr;
} ผลลัพธ์
Runtime error for accessing null pointer values
กำลังพยายามเข้าถึงค่าตัวชี้ null
โค้ดตัวอย่าง
#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.