The language C does not provide direct support for exception handling.
This means that there is no mechanism to trap errors. In some cases, the code may continue to execute with errors.
In such situations, the compiler’s behavior becomes unpredictable, or undefined
.
Anything can happen, which may include the following:
Program Crash: The entire program may crash citing any error as the reason
Unpredictable Results: The program may generate incorrect or garbage output
Data Corruption: The compiler may corrupt data which could lead to several other problems
Let’s look at an example for undefined
behavior:
#include <stdio.h>#include <stdlib.h>int main(){// We will try to access arr[5] which is out of boundsint arr[5] = {0, 1, 2, 3, 4};int i = 0;for(; i <= 5; i++)printf("%d\n", arr[i]);return 0;}
In the above case, we try to access the 5th element in the array, which is out of bounds.
The compiler continues execution, regardless of the error. As a result, the 5th output is undefined
.
There is no way to predict what we will get as our 5th output.
The tolerance for
undefined
behavior in C allows for faster compilation of code due to fewer checks.
Free Resources