undeclaredWhat does "undeclared" mean?
The C compiler stops with "undeclared" when a line uses a name it has not seen yet: a typo, a missing #include, or a function written further down.
What the compiler is telling you
main.c(6): `bonsu' undeclared
int total = score + bonsu;
^~~~~The compiler reads your file from the top, once. Every name must be declared before the line that uses it. This message means: "on line 6 you used bonsu, and I have never seen that name".
The usual reasons:
- A typo.
bonsuinstead ofbonus. Capitals count too:Scoreis notscore. - Declared too late. A function written below
main, with no prototype above it. - Out of scope. The variable was declared inside another
{ }block, or another function, so it no longer exists here. - A missing #include. Library names like
strlenonly exist after#include <string.h>.
How to find it
The message gives the line in brackets, and the ^~~~ marks the exact name. Search the file for where that name is declared. If you find it spelled differently, fix the spelling. If it is below this line, or inside a different block, move it up or add a prototype. If it is a library function, check its #include.
Run it: one letter swapped
Press Run and read the error from the bottom up.
#include <stdio.h>
int main(void) {
int score = 120;
int bonus = 30;
int total = score + bonsu;
printf("total %d\n", total);
return 0;
}
The basket total nobody can see
This adds up a shopping basket in pence. It does not compile. Read the message, then fix it so it prints basket 1819.
#include <stdio.h>
int main(void) {
int prices[4] = {250, 450, 120, 999};
for (int i = 0; i < 4; i++) {
int total = 0;
total += prices[i];
}
printf("basket %d\n", total);
return 0;
}