1. 目的
C++ の auto キーワードについて、型推論の仕組みと使い方、注意点を整理する。
2. 目次
3. 概要
auto は変数の型をコンパイラに自動で判断させるキーワード。
型名の記述を省略できる一方、意図しない型になる場合もあるため注意点を合わせて確認する。
4. 内容
4.1 auto キーワード
4.1.1 auto とは
型をコンパイラに自動で判断させる仕組み。
auto x = 10;→ int と判断されるauto y = 3.14;→ double と判断されるauto z = true;→ bool と判断される
#include <iostream> using namespace std; int main() { auto x = 10; // int と判断される auto y = 3.14; // double と判断される auto z = true; // bool と判断される cout << x << endl; cout << y << endl; cout << z << endl; return 0; }
結果:https://paiza.io/projects/vYg_Za21eG2lxF8OOkkgDQ?language=cpp
4.1.2 なぜ便利か
型名が長いときに特に役立つ。
#include <iostream> #include <vector> using namespace std; int main() { vector<int> scores = {10, 20, 30}; // 型を自分で書く(長い) std::vector<int>::iterator it1 = scores.begin(); // auto を使う(短い) auto it2 = scores.begin(); cout << *it1 << endl; cout << *it2 << endl; return 0; }
結果:https://paiza.io/projects/zK1wXRu6qFEtDtmObp6aXg?language=cpp
4.1.3 auto を使う場合の注意点
(1) 初期値が必ず必要
初期値がないと型を決められないため、コンパイルエラーになる。
int main() { // auto x; // エラー:型が決められない(コメントを外すとコンパイルエラーになります) auto x = 0; // OK return 0; }
結果:https://paiza.io/projects/EkGeSIQoi7l5H3bzQSXEPg?language=cpp
(2) 意図しない型になることがある
整数同士の割り算は int のまま扱われ、小数点以下が切り捨てられる。
#include <iostream> using namespace std; int main() { auto a = 5; // int auto b = 5.0; // double auto c = 1 / 2; // 結果は 0(int の割り算) auto d = 1.0 / 2; // 結果は 0.5(double の割り算) cout << c << endl; // 0 cout << d << endl; // 0.5 return 0; }
結果:https://paiza.io/projects/7JhQAcWe5Nz7tIW55JxGPg?language=cpp
(3) 文字列の型に注意
"..." は const char* と判断されるため、string 型のメソッドは使えない。
#include <iostream> #include <string> using namespace std; int main() { auto s1 = "hello"; // const char*(C言語の文字列) auto s2 = string("hello"); // string(C++の文字列) // s1 は string のメソッドが使えない // cout << s1.length(); // エラーになる cout << s2.length() << endl; // OK:5 と表示 return 0; }
結果:https://paiza.io/projects/C0UcgENReChhMR8OfehdAw?language=cpp
(4) 参照と組み合わせるとき
auto は値のコピーになる。参照にしたい場合は auto& と書く。
#include <iostream> using namespace std; int main() { int score = 100; auto a = score; // int のコピー(score とは別物) auto& b = score; // int& の参照(score の別名) a = 200; // score は変わらない b = 200; // score も 200 になる cout << "a=" << a << " score=" << score << endl; return 0; }
結果:https://paiza.io/projects/Jlne8x0fcbIhcZy04WQXiA?language=cpp















