error: 'x' was not declared in this scope の原因と直し方
宣言していない変数を使ったときに出るエラーです。多くの場合はタイプミスで、g++は似た名前の宣言済み変数があれば「did you mean 'total'?」のように候補を提案してくれます。
エラーメッセージの読み方
main.cpp:4:18: error: 'toal' was not declared in this scope; did you mean 'total'?
main.cpp- ファイル名
4- 行番号
18- 列番号 — この位置でg++が構文解析に失敗しました
'toal' was not declared in this scope; did you mean 'total'?- 内容 — 期待していたもの、または受け付けられなかったもの
このエラーが出る典型パターン
パターン1
1 #include <iostream> 2 int main() { 3 int total = 5; 4 std::cout << toal << std::endl; ^ 5 return 0; 6 }
main.cpp:4:18: error: 'toal' was not declared in this scope; did you mean 'total'?
totalとtoalは文字が入れ替わっただけの別名です。g++は似た名前の宣言済み変数を見つけると「did you mean」で提案してくれますが、実際に直すのは自分です。
直し方: toal を total にします。
広告
広告スロット(未設定)
パターン2
1 #include <iostream> 2 int main() { 3 int score = 90; 4 std::cout << scroe << std::endl; ^ 5 return 0; 6 }
main.cpp:4:18: error: 'scroe' was not declared in this scope; did you mean 'score'?
scoreのタイプミスであるscroeという名前は宣言されていないため、コンパイラは未知の識別子として扱います。
直し方: scroe を score にします。
パターン3
1 #include <iostream> 2 int main() { 3 int width = 10; 4 int height = 20; 5 std::cout << (width * hight ) << std::endl; ^ 6 return 0; 7 }
main.cpp:5:27: error: 'hight' was not declared in this scope; did you mean 'height'?
heightをhightと書き間違えると、コンパイラはそのような名前を知らないため即座にエラーにします。
直し方: hight を height にします。
よくある誤解
「コンパイラが賢く直してくれる」わけではありません。提案(did you mean)はあくまでヒントであり、実際にコードを書き換えるのは自分です。提案された名前が意図と違う変数であるケースもあります。
まとめ
error: 'x' was not declared in this scopeは初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。