11.7 Ellipsis (and why to avoid them)

주홍영·2022년 3월 14일
0

Learncpp.com

목록 보기
121/199

https://www.learncpp.com/cpp-tutorial/ellipsis-and-why-to-avoid-them/

Ellipsis (...) 인 생략부호

An ellipsis example

ellipsis에 대해 배우는 가장 좋은 방법은 예제를 보는 것입니다. 따라서 생략 부호를 사용하는 간단한 프로그램을 작성해 보겠습니다. 정수 묶음의 평균을 계산하는 함수를 작성한다고 가정해 보겠습니다. 우리는 다음과 같이 할 것입니다:

#include <iostream>
#include <cstdarg> // needed to use ellipsis

// The ellipsis must be the last parameter
// count is how many additional arguments we're passing
double findAverage(int count, ...)
{
    int sum{ 0 };

    // We access the ellipsis through a va_list, so let's declare one
    std::va_list list;

    // We initialize the va_list using va_start.  The first parameter is
    // the list to initialize.  The second parameter is the last non-ellipsis
    // parameter.
    va_start(list, count);

    // Loop through all the ellipsis arguments
    for (int arg{ 0 }; arg < count; ++arg)
    {
         // We use va_arg to get parameters out of our ellipsis
         // The first parameter is the va_list we're using
         // The second parameter is the type of the parameter
         sum += va_arg(list, int);
    }

    // Cleanup the va_list when we're done.
    va_end(list);

    return static_cast<double>(sum) / count;
}

int main()
{
    std::cout << findAverage(5, 1, 2, 3, 4, 5) << '\n';
    std::cout << findAverage(6, 1, 2, 3, 4, 5, 6) << '\n';
}

ellipsis는 major하게 사용할 것 같지 않아서 자세히 다루지는 않겠다

profile
청룡동거주민

0개의 댓글