Examples of Errors During Compilation Stages (Lexical, Syntax, Semantic)

Lexical Errors

ExampleDescription/Explanation
int n%mber = 5;Illegal character % in identifier.
floar x = 5.0;Misspelling of keyword float as floar.
int 1stNumber = 1;Identifiers cannot start with a digit.
#incldue <stdio.h>Misspelling of directive #include.
double price = 45.6L;Incorrect use of float literal suffix (L is for long int).
char* str = 'Hello';Single quotes used instead of double quotes for string literal.

Syntax Errors

ExampleDescription/Explanation
int a = 5Missing semicolon at the end of the statement.
if (a < 5) { int b = 0;Missing closing brace } for the if statement block.
for (int i = 0 i < 10; i++)Missing semicolon in the for loop declaration.
printf("%d", a, b);Mismatch in the number of arguments in printf.
int array[5 = {1, 2, 3, 4, 5};Syntax error in array initialization (should be array[5] = {1, 2, 3, 4, 5};).
while(a < 5)Missing opening or closing braces for the while loop body.
int x = (2, 3);Incorrect use of the comma operator in assignment.

Semantic Errors

ExampleDescription/Explanation
int a = "hello";Type mismatch: assigning a string to an integer variable.
int a; return a;Using uninitialized variable a.
int a = 5 / 0;Division by zero.
char *str = malloc(10); free(str); str[0] = 'A';Using a pointer str after it has been freed.
int* ptr; *ptr = 10;Dereferencing an uninitialized pointer ptr.
int arr[5]; arr[10] = 50;Array index out of bounds.
double result = sqrt(-1);Passing invalid argument to a function (e.g., square root of a negative number).
FILE *fp = fopen("nonexistent.txt", "r"); if(fp) { /* ... */ }Incorrect error checking on fopen. Should be if(!fp) for error checking.

© 2024  Vedesh Kungebeharry. All rights reserved. 

Leave a comment