Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Undefined Behaviour ใน C และ C++


ดูโค้ด C และ C++ ลองทายผลลัพธ์ โค้ดเหล่านี้จะสร้าง runtime errors

1. Divide By Zero เป็น undefined behaviour

โค้ดตัวอย่าง

#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. ใช้ตัวแปรที่ยังไม่ initialize

โค้ดตัวอย่าง

#include <iostream> using namespace std; int main() { bool x; if(x == true) cout << "true value"; else cout << "false value"; }

ผลลัพธ์

false value (อาจต่างกันใน compiler ต่างๆ)

3. เข้าถึงค่า null pointer

โค้ดตัวอย่าง

#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. บาง compiler อาจคืนค่า arbitrary ไม่ error

5. เกินขอบเขต signed int

โค้ดตัวอย่าง

#include <iostream> using namespace std; int main() { int x = INT_MAX; cout << "x + 1: " << x + 1; }

ผลลัพธ์

x + 1: -2147483648 วิ่งกลับไปเป็นค่าต่ำสุดของ signed int

6. พยายามเปลี่ยนตัวอักษรใน string literals

โค้ดตัวอย่าง

#include <iostream> using namespace std; int main() { char *str = "Hello World"; str[2] = 'x'; cout << str; }

ผลลัพธ์

Runtime error เพราะพยายามเปลี่ยนค่าตัวแปร constant