`a

`auto` 에서 C++

1개의 연습 문제

`auto` 소개

C++의 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는 코드를 깔끔하게 정리하고 유지보수성을 높여줘요.
  • 반복자 기반 알고리즘: 알고리즘에서 반복자를 사용하는 방법을 단순하게 만들어 코드 가독성을 높여줘요.
GitHub에서 편집 링크가 새 창이나 탭에서 열려요

`auto` 배우기

연습이 잠겨 있어요

`auto` 개념을 연습하려면 연습 문제 1개를 더 잠금 해제해요