Code Fix

中級

C++でerror: assignment of read-only variable が出る原因と直し方

constを付けて宣言した変数に、あとから値を代入しようとしたときに出るエラーです。constは「この変数は初期化後に変更しない」という約束をコンパイラに伝えるものです。

エラーメッセージの読み方

main.cpp:4:11: error: assignment of read-only variable 'limit'
main.cpp
ファイル名
4
行番号
11
列番号 — この位置でg++が構文解析に失敗しました
assignment of read-only variable 'limit'
内容 — 期待していたもの、または受け付けられなかったもの

このエラーが出る典型パターン

パターン1

 1  #include <iostream>
 2  int main() {
 3      const int limit = 100;
 4      limit      = 200;
             ^
 5      std::cout << limit << std::endl;
 6      return 0;
 7  }
main.cpp:4:11: error: assignment of read-only variable 'limit'

constを付けた変数はコンパイラが「変更しない」という約束を強制します。値を変えたいなら、別のconstでない変数を新しく用意します。

直し方: limitint limit2 にします。

この問題を解いてみる →

広告
広告スロット(未設定)

パターン2

 1  #include <iostream>
 2  int main() {
 3      const int maxSpeed = 60;
 4      maxSpeed     = 80;
              ^
 5      std::cout << maxSpeed << std::endl;
 6      return 0;
 7  }
main.cpp:4:14: error: assignment of read-only variable 'maxSpeed'

maxSpeedはconstとして宣言されているため、その名前への代入はコンパイル時に拒否されます。

直し方: maxSpeedint newSpeed にします。

この問題を解いてみる →

パターン3

 1  #include <iostream>
 2  int main() {
 3      const int taxRate = 10;
 4      taxRate     = 20;
             ^
 5      std::cout << taxRate << std::endl;
 6      return 0;
 7  }
main.cpp:4:13: error: assignment of read-only variable 'taxRate'

「constは目印にすぎない」というのは誤解で、実際にコンパイラがチェックする言語機能です。

直し方: taxRateint newRate にします。

この問題を解いてみる →

よくある誤解

「constは単なる目印(コメント代わり)」というのは誤解です。C++のconstはコンパイラが実際にチェックする言語機能で、違反があればコンパイルそのものが止まります。

まとめ

C++でerror: assignment of read-only variable が出る原因と直し方は中級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。

演習をはじめる

関連するエラー

広告
広告スロット(未設定)