首頁 >後端開發 >C++ >在C和C++中的未定義行為

在C和C++中的未定義行為

WBOY
WBOY轉載
2023-08-28 13:09:05926瀏覽

在C和C++中的未定義行為

在這裡,我們將看到一些C和C 程式碼,並嘗試猜測結果。這些程式碼將產生一些運行時錯誤。

1. 除以零的錯誤是未定義的。

範例程式碼

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

Output

Runtime error for divide by zero operation

2. Trying to use uninitialized variable.

Example Code

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

Output

false value (This may differ in different compilers)

3. Trying to access null pointer values.

Example Code

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

Output

Runtime error for accessing null pointer values

4. Trying to access null pointer values.

#4. Trying to access null pointer values.

##4. #Example Code

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

Output

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;
}

Output

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] = &#39;x&#39;;
   cout << str;
}
Output###
Runtime error because we are trying to change the value of some constant variables.
####

以上是在C和C++中的未定義行為的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除