C Errors
Understanding and handling errors in C programming
⚠️ What are C Errors?
C errors are mistakes in code that prevent programs from compiling or running correctly. Understanding different error types helps you write better, more reliable C programs and debug issues effectively.
// This code has a syntax error
#include <stdio.h>
int main() {
printf("Hello World") // Missing semicolon!
return 0;
}
Types of C Errors
Syntax Errors
Mistakes in C language rules
// Missing semicolon
printf("Hello")
Runtime Errors
Errors that occur during execution
// Division by zero
int result = 10 / 0;
Logic Errors
Code runs but produces wrong results
// Wrong condition
if (age = 18) // Should be ==
Linker Errors
Problems connecting code modules
// Undefined function
void missing_function();
🔹 Common Syntax Errors
Syntax errors are the most frequent mistakes beginners make and prevent compilation entirely. Missing semicolons, incorrect bracket placement, mismatched parentheses, and typos in keywords are typical syntax errors. The compiler catches these errors and reports them with line numbers and descriptions. Pay careful attention to error messages, as they often point directly to the problem or the line before it. Using an IDE with syntax highlighting and real-time error detection helps catch syntax errors immediately before compilation.
// ❌ WRONG - Missing semicolon
#include <stdio.h>
int main() {
printf("Hello World") // Error here!
return 0;
}
// ✅ CORRECT - With semicolon
#include <stdio.h>
int main() {
printf("Hello World"); // Fixed!
return 0;
}
Compiler Error:
🔹 Runtime Error Example
Runtime errors occur when a program compiles successfully but crashes or behaves unexpectedly during execution. These include segmentation faults from accessing invalid memory, division by zero operations, dereferencing null pointers, and array index out-of-bounds errors. Unlike syntax errors, runtime errors are harder to detect because the compiler cannot catch them. Use debugging techniques and error handling mechanisms to identify and fix runtime errors before they crash your program in production environments.
// ❌ This will cause a runtime error
#include <stdio.h>
int main() {
int numbers[3] = {1, 2, 3};
// Accessing beyond array bounds
printf("%d", numbers[5]); // Dangerous!
return 0;
}
// ✅ SAFE version with bounds checking
#include <stdio.h>
int main() {
int numbers[3] = {1, 2, 3};
int index = 2; // Valid index
if (index < 3) {
printf("%d", numbers[index]);
}
return 0;
}
Safe Output:
🔹 Logic Error Detection
Logic errors are particularly tricky because code compiles and runs without crashing but produces incorrect results. The program executes without errors, yet the output doesn't match expected behavior. These errors stem from incorrect algorithm implementation, flawed conditional statements, or wrong loop logic. To detect logic errors, trace program execution with printf() statements, verify loop conditions and iteration counts, check conditional logic carefully, and test with multiple input values including edge cases to expose incorrect behavior.
// ❌ Logic error - using assignment instead of comparison
#include <stdio.h>
int main() {
int age = 20;
if (age = 18) { // Wrong! This assigns 18 to age
printf("You are exactly 18");
}
return 0;
}
// ✅ CORRECT - using comparison operator
#include <stdio.h>
int main() {
int age = 20;
if (age == 18) { // Correct comparison
printf("You are exactly 18");
} else {
printf("You are %d years old", age);
}
return 0;
}
Correct Output:
🔹 Error Prevention Tips
Following best practices during code development prevents many errors and makes debugging unnecessary. Write code incrementally and test each section thoroughly before adding more functionality. Use meaningful variable names to reduce confusion, add comments explaining complex logic, implement input validation to reject invalid data early, and use compiler warnings effectively by enabling all warning flags. Review code carefully before committing, follow consistent formatting conventions, and maintain good coding practices throughout development.
Prevention Strategies:
- Always use semicolons: End every statement with ;
- Check array bounds: Never access beyond array size
- Initialize variables: Give variables starting values
- Use == for comparison: Don't confuse with = (assignment)
- Match braces: Every { needs a closing }
// Good error prevention example
#include <stdio.h>
int main() {
// Initialize variables
int num1 = 0, num2 = 0, result = 0;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Check for division by zero
if (num2 != 0) {
result = num1 / num2;
printf("Result: %d", result);
} else {
printf("Error: Cannot divide by zero!");
}
return 0;
}