Home > Backend Development > C++ > Undefined behavior in C and C++

Undefined behavior in C and C++

WBOY
Release: 2023-08-28 13:09:05
forward
926 people have browsed it

Undefined behavior in C and C++

Here we will see some C and C code and try to guess the results. These codes will generate some runtime errors.

1. The divide-by-zero error is undefined.

Example Code

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

Output

Runtime error for divide by zero operation
Copy after login

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";
}
Copy after login

Output

false value (This may differ in different compilers)
Copy after login

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;
}
Copy after login

Output

Runtime error for accessing null pointer values
Copy after login

4. Trying to access null pointer values.

Example Code

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

Output

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

5. The limit for signed integers was exceeded.

Sample Code

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

Output

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

6. Try changing some characters in the string literal.

Sample Code

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

Output

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

The above is the detailed content of Undefined behavior in C and C++. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template