Code Fix

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

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

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

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

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

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

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

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

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

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