auto 키워드C++에서 auto 키워드는 C++11에 도입된 강력한 기능으로, 타입을 추론해서 변수를 선언할 때 사용해요.
컴파일러는 초기화식에 따라 변수의 타입을 추론하는데, 덕분에 코드가 더 읽기 쉽고 유지보수하기 쉬워져요.
auto로 변수를 선언하는 다음 예시를 살펴봐요:
auto dragon_population{3}; // dragon_population is deduced as an integer
auto westeros{7.7777}; // westeros is deduced as a double
auto wedding_location{"The Twins"}; // wedding_location is deduced as a const char*, not std::string
각각의 경우에 변수의 타입은 초기화에 사용된 값으로부터 추론돼요.
auto 키워드는 명시적인 타입을 반복해서 쓰는 번거로움을 줄여서 코드를 더 간결하고 읽기 쉽게 만들어줘요.
const std::vector<std::string> pigeon_pie{"flour", "butter", "pigeon", "salt"};
auto purple_wedding_pie{pigeon_pie};
purple_wedding_pie.emplace_back("the strangler");
이 코드에서 auto는 purple_wedding_pie의 타입을 std::vector<std::string>으로 추론해서, 타입을 다시 명시할 필요가 없어요.
auto 키워드는 다양한 C++ 구문과 함께 쓸 수 있어서, 현대 C++ 프로그래밍에서 활용도가 높은 도구예요.
auto& element{array[0]}; // reference to an element
const auto object{otherObject}; // const type version of otherObject's type
auto* ptr{&x}; // pointer to x with the same type as x, but as a pointer.
이후 개념에서는 람다 표현식, 범위 기반 for문, 반복자와 함께 쓰이는 auto 키워드를 자주 보게 될 거예요.
auto가 특히 유용해요.auto는 코드를 깔끔하게 정리하고 유지보수성을 높여줘요.