Code Fix

中級C++でerror: assignment of read-only variable が出る原因と直し方 › パターン1

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

constを付けて宣言した変数に、あとから値を代入しようとしたときに出るエラーです。

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

空欄を埋めてコンパイル・実行を通す

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

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

constは「この変数は初期化後に変更しない」という約束をコンパイラに伝えるものです。

このエラーの解説と類題をまとめて見る →

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