Semantic Error in C
Introduction:
The majority of programs have mistakes. Grammar problems result from missing elements of the language, such as semicolons and parentheses. In addition to this, the time of execution problems occur when the program is executed.
There are at least 5 distinct mistake kinds in C:
- syntax errors
- Runtime errors
- Logical errors
- Related errors
- Semanticerrors
Semantic Error in C:
Semantic errors happen if an expression is grammatically valid yet meaningless. These resemble errors in grammar. A semantics error could happen if a keyword is put to the far left of the assign function.
- The semantic error, sometimes referred to as a reasoning error, happens whenever the program correctly generates and fails to produce the desired or accurate outputs.
- Since the program is semantically accurate yet behaves unexpectedly, such issues might be difficult to spot.
- Usually, semantic mistakes come to light through testing or debugging.
These are a few typical C instances of semantic mistakes:
1. Inadvertently employing the erroneous parameter or operators: When you unintentionally employ the inaccurate parameter or function in an equation, the outcome may be inaccurate.
Example Code:
#include <stdio.h> int main() { int p = 2; int q = 8; int result = p + q; printf("%d",result); return 0; }
Output
2. Off-by-one errors: They happen if indexing computations are wrong when you read or alter storage beyond an array's boundaries.
Example code:
#include <stdio.h> int main() { int arr[3]; for (int i = 0; i <= 3; i++) { arr[i] = i; } printf("%d",arr[3]); return 0; }
Output:
3. Incorrect conditional logic: Unsound dependent reasoning Unintended flow of control might result from using the incorrect circumstances in if expressions or looping.
Example code:
#include <stdio.h> int main() { int x = 3; if (x = 5) { printf("x is 5\n"); } return 0; }
Output:
4. Not handling special cases: failing to handle exceptional instances. Runtime mistakes are possible if specified circumstances are not handled, like dividing by zero.
Example code:
#include <stdio.h> int main() { int a = 5; int b = 0; int result = a / b; printf("%d",result); return 0; }
Output:
5. Inconsistent variable types: different kinds of variables Lacking proper type in the casting process, combining disparate data types can result in unanticipated outcomes.
Example code:
#include <stdio.h> int main() { int a = 3; float b = 3.5; int result = a + b; printf("%d",result); return 0; }
Output: