Apply for Zend Framework Certification Training

c

< Standard C Libraries with Examples Last >




Types of Errors in C
While writing and executing a C program, you may encounter three common types of errors:
Compilation Errors
Runtime Errors
Logical Errors
1. Compilation Errors
A compilation error occurs when the C compiler finds a mistake in the program's syntax or structure.
The program will not compile until the error is corrected.
Example 1: Missing semicolon
#include <stdio.h>
int main(){
    int a = 10
    printf("%d", a);
    return 0;
}
Error: Missing ; after int a = 10.
Correct Program
#include <stdio.h>
int main(){
    int a = 10;
    printf("%d", a);
 
    return 0;
}
Example 2: Undeclared variable
#include <stdio.h>
int main(){
    int a = 10;
    printf("%d", b);
    return 0;
}
Here, b has not been declared.
Typical compiler message:
error: 'b' undeclared
2. Runtime Errors
A runtime error occurs while the program is running.
The program may compile successfully, but something goes wrong during execution.
Example 1: Division by zero
#include <stdio.h>
int main(){
    int a = 10;
    int b = 0;
    printf("%d", a / b);
    return 0;
}
The program compiles, but 10 / 0 is invalid and can cause a runtime failure.
Example 2: Invalid memory access
#include <stdio.h>
int main(){
    int arr[3] = {10, 20, 30};
    printf("%d", arr[10]);
    return 0;
}
arr[10] is outside the valid range of the array (0 to 2), resulting in undefined behavior.
3. Logical Errors
A logical error occurs when the program runs successfully but produces the wrong output because the logic or formula is incorrect.
Example: Incorrect addition
Suppose we want to calculate the average of two numbers.
#include <stdio.h>
int main(){
    int a = 10, b = 20;
    int average;
    average = a + b / 2;
    printf("Average = %d", average);
    return 0;
}
Output
Average = 20
But the correct average is:
(10 + 20) / 2 = 15
The problem is operator precedence. Division is performed before addition.
 
Correct Program
#include <stdio.h>
int main(){
    int a = 10, b = 20;
    int average;
    average = (a + b) / 2;
    printf("Average = %d", average);
    return 0;
}
Correct Output
Average = 15
Quick Comparison
Error Type When it occurs Program runs? Example
Compilation Error During compilation No Missing ;
Runtime Error During execution May stop/fail Division by zero
Logical Error Due to incorrect logic Yes Wrong formula
Easy way to remember
Compilation Error → Program cannot compile
Runtime Error → Program compiles but fails while running
Logical Error → Program runs but gives the wrong answer

< Standard C Libraries with Examples Last >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top