Computer >> Máy Tính >  >> Lập trình >> lập trình C

Hành vi không xác định trong C và C ++

Ở đây chúng ta sẽ thấy một số Mã C và C ++. và cố gắng đoán kết quả. Các mã sẽ tạo ra một số lỗi thời gian chạy.

1. Lỗi Chia cho Bằng không là không xác định.

Mã mẫu

#include <iostream>
using namespace std;
int main() {
   int x = 10, y = 0;
   int z = x / y;
   cout << "Done" << endl;
}

Đầu ra

Runtime error for divide by zero operation

2. Cố gắng sử dụng biến chưa được khởi tạo.

Mã mẫu

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

Đầu ra

false value (This may differ in different compilers)

3. Cố gắng truy cập các giá trị con trỏ null.

Mã mẫu

#include <iostream>
using namespace std;
int main() {
   int *ptr = NULL;
   cout << "The pointer value is: " << *ptr;
}

Đầu ra

Runtime error for accessing null pointer values

4. Đang cố gắng truy cập các giá trị con trỏ null.

Mã mẫu

#include <iostream>
using namespace std;
int main() {
   int array[10];
   for(int i = 0; i<=10; i++) {
      cout << array[i] << endl;
   }
}

Đầu ra

Runtime error for accessing item out of bound.
Some compiler may return some arbitrary value, not return any error

5. Vượt quá giới hạn int đã ký.

Mã mẫu

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

Đầu ra

x + 1: -2147483648
circulate to the minimum number of signed int

6. Đang cố gắng thay đổi một số ký tự trong chuỗi ký tự.

Mã mẫu

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

Đầu ra

Runtime error because we are trying to change the value of some constant variables.