const
定数
const
定数を使用することで後から値の変更ができなくなる
複数人で開発する場合に後から値を変更できなくするために使うことができる
const
の使い方
const int x = 10;
後から値の変更ができない
#include <iostream>
using namespace std;
int main(){
const int x = 10;
x = 15;
cout << x << endl;
return 0;
}
ビルドを開始しています...
C:\MinGW\bin\g++.exe -fdiagnostics-color=always -g C:\Git\C++\test.cpp -o C:\Git\C++\test.exe
C:\Git\C++\test.cpp: In function 'int main()':
C:\Git\C++\test.cpp:7:5: error: assignment of read-only variable 'x'
7 | x = 15;
| ~~^~~~
ビルドが完了しましたが、エラーが発生しました。
値の初期化をする必要がある
#include <iostream>
using namespace std;
int main(){
const int x;
x = 10;
cout << x << endl;
return 0;
}
ビルドを開始しています...
C:\MinGW\bin\g++.exe -fdiagnostics-color=always -g C:\Git\C++\test.cpp -o C:\Git\C++\test.exe
C:\Git\C++\test.cpp: In function 'int main()':
C:\Git\C++\test.cpp:6:13: error: uninitialized const 'x' [-fpermissive]
6 | const int x;
| ^
C:\Git\C++\test.cpp:7:5: error: assignment of read-only variable 'x'
7 | x = 10;
| ~~^~~~
ビルドが完了しましたが、エラーが発生しました。