1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ⑥~const定数~

Last updated at Posted at 2022-07-09

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;
      |   ~~^~~~

ビルドが完了しましたが、エラーが発生しました。

次の記事

【C++】基礎を学ぶ⑦~cinで入力を受け取る~

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?