Error messages look frightening, but they all have the same shape:
marks.c:6:5: error: expected ';' before 'return'
File marks.c, line 6, column 5, the kind (error or warning), then the message. Most editors let you click it to jump to the line.
Three rules
- Fix the first error first, then compile again. One missing
;can confuse the compiler into reporting ten more errors that are not real. - Look at the line before. "Expected
;beforereturn" on line 6 means the;is missing at the end of line 5. - Read the whole message, including the lines with
^under your code: they point at the exact spot.
Common messages
| Message | Usual cause |
|---|---|
expected ';' before ... | a missing ; at the end of the line above |
'totl' undeclared | a typo in a name, or the variable was declared inside another block |
implicit declaration of function 'prinf' | a typo, a missing #include, or a function used before its prototype |
too few arguments to function 'max' | the call does not match the function's parameters |
assignment to 'int' from 'char *' | the types do not match; check * and & |
undefined reference to 'average' | from the linker: the function is declared but never defined, or its .c file is not on the command line |
undefined reference to 'main' | the program has no main (or it is spelled differently) |
When the program compiles but is wrong
#include <stdio.h>
int main(void) {
int marks[3] = {70, 85, 90};
int total = 0;
for (int i = 0; i <= 3; i++) {
total += marks[i];
}
printf("total %d\n", total);
return 0;
}This program compiles without an error, and with -Wall -Wextra gcc does not even warn (only with -O2 does it sometimes notice). But the loop runs while i <= 3, so it reads marks[3], one past the end. Compiled with gcc, it prints a wrong total (whatever was in memory next to the array) or crashes with Segmentation fault, and it can behave differently on another computer. Press Visualize: StepVioz stops at the exact line and shows you the array. On your own computer, gcc -fsanitize=address -g (Linux and macOS) gives you similar checks.
A compiler checks that your code is legal C. Only running it, testing it and watching it (the next lessons) can show that it is right.
Quick check
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.