Software/Embedded system

fmt 와 Variadic function 정리

neovaga 2022. 7. 10. 00:01
반응형

 fmt 는 format을 줄여서 표현한 부분이다. Formatted I/O with functions 이고 대표적으로 printf 와 scanf 가 있다. 

 

 Variadic function이란 가변 함수란 의미이다. 정의가 되어 있는 않는 인수를 가지고 함수를 만들수 있다는 의미이다. printf 가 해당하는 함수 이다. A variadic function is a function of indefinite arguments or operands. 

 

 C 언어에서는 stdarg.h header파일을 통해서 api를 사용할 수 있다.  The stdarg.h is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments. 

 

 void func( char a, int b, ...);  보통 ...을 통해서 정의를 한다. 반드시 하나이상의 매개변수를 넣어 줘야한다. 

 

 간단하게 예제를 참고하면 이해가 되기 싶다. Printf코드를 보면서 이해를 하면 더 좋을 것 같다. 

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

double average(int count, ...)
{
    va_list ap;
    int j, arg=0;
    double sum = 0;

    va_start(ap, count); //Requires the last fixed paramter (to get the address)
    for (j = 0; j < count; j++)
    {
        arg = va_arg(ap, int); //Increments ap to the next argument.
        printf("Argument[%d]:%d\n", j, arg);
        sum += arg;
    }
    va_end(ap);
    return sum / count;
}

int main(int argc, char **argv)
{
    printf("Average: %f\n", average(atoi(argv[1]),atoi(argv[2]),atoi(argv[3])));

    return 0;
}

//결과 돌려 보면 아래와 같이 나온다.
03_network ./fmt 2 10 5
Argument[0]:10
Argument[1]:5
Average: 7.500000
반응형