C Common Mistakes
In this page:
Missing Semicolons
Every executable C statement must end with a semicolon, and omitting even one usually produces a compiler error pointing at the following line rather than the actual missing semicolon, which can make the real cause of the error confusing to track down at first.
Example: Missing Semicolons
#include <stdio.h>
int main() {
int x = 5;
printf("%d", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Uninitialized Variables
Unlike some languages, C does not automatically zero-initialize local variables, so a freshly declared variable holds whatever leftover bit pattern happened to already be sitting in that stack memory. Reading it before explicitly assigning a value produces unpredictable, garbage results.
Example: Uninitialized Variables
#include <stdio.h>
int main() {
int x = 0;
printf("%d", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Missing Ampersand (&) in scanf
scanf() needs the memory address of the variable it's writing into, not the variable's value, so a call like scanf("%d", age); (missing the &) writes to whatever random address happens to be stored in age, often crashing the program instead of reading the intended input.
Example: Missing Ampersand (&) in scanf
#include <stdio.h>
int main() {
int age;
sscanf("25", "%d", &age);
printf("%d", age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Array Index Out of Bounds
C performs no automatic bounds checking on array access, so reading or writing past an array's declared size doesn't raise an error — it silently accesses whatever memory happens to sit adjacent to the array, which can corrupt unrelated variables or crash the program unpredictably.
Example: Array Index Out of Bounds
#include <stdio.h>
int main() {
int arr[5] = {1,2,3,4,5};
printf("%d", arr[4]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Infinite Loop Triggers
A loop only terminates once its condition becomes false, so forgetting to update the loop's controlling variable inside the loop body (like forgetting i++ in a for/while loop) leaves that condition permanently true and the loop runs forever.
Example: Infinite Loop Triggers
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- C typedef
- C Type Casting
- C Bit Fields
- C Variable Length Arrays
- C Command Line Arguments
- C Function Pointers
- C Callback Functions
- C Multidimensional Pointer
- C string.h Functions
- C stdlib.h Functions
- C math.h Functions
- C time.h Functions
- C ctype.h Functions
- C errno.h
- C assert.h
- C Error Handling
- C Debugging Techniques
- C Code Style & Best Practices
- C Common Mistakes
- C Interview Questions