Programing

함수를 C에서 매개 변수로 어떻게 전달합니까?

crosscheck 2020. 10. 4. 10:27
반응형

함수를 C에서 매개 변수로 어떻게 전달합니까?


데이터 집합에 대해 매개 변수로 전달 된 함수를 수행하는 함수를 만들고 싶습니다. 함수를 C에서 매개 변수로 어떻게 전달합니까?


선언

함수 매개 변수를받는 함수의 프로토 타입은 다음과 같습니다.

void func ( void (*f)(int) );

이것은 매개 변수 fvoid반환 유형을 갖고 단일 int매개 변수 를 취하는 함수에 대한 포인터가 될 것임을 나타냅니다 . 다음 함수 ( print)는 func적절한 유형이므로 매개 변수로 전달할 수있는 함수의 예입니다 .

void print ( int x ) {
  printf("%d\n", x);
}

기능 호출

함수 매개 변수를 사용하여 함수를 호출 할 때 전달 된 값은 함수에 대한 포인터 여야합니다. 이를 위해 함수 이름 (괄호 없음)을 사용합니다.

func(print);

을 호출 func하여 인쇄 함수를 전달합니다.

기능 본체

모든 매개 변수와 마찬가지로 func는 이제 함수 본문의 매개 변수 이름을 사용하여 매개 변수 값에 액세스 할 수 있습니다. func가 숫자 0-4에 전달되는 함수를 적용한다고 가정 해 봅시다. 먼저 print를 직접 호출하는 루프의 모습을 고려해보십시오.

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
  print(ctr);
}

이후 func의 매개 변수 선언은 그 말한다 f원하는 기능에 대한 포인터의 이름, 우리는 경우 첫 번째 기억 f의 포인터 다음 *f물건입니다 f(즉, 함수 지점 print이 경우). 결과적으로 위의 루프에서 모든 인쇄 항목을 다음으로 대체하십시오 *f.

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

에서 http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html


이 질문은 이미 함수 포인터를 정의하는 데 대한 답을 가지고 있지만, 특히 응용 프로그램 주위로 전달하려는 경우 매우 지저분해질 수 있습니다. 이 불쾌감을 피하기 위해 함수 포인터를 더 읽기 쉬운 것으로 typedef하는 것이 좋습니다. 예를 들면.

typedef void (*functiontype)();

void를 반환하고 인수를받지 않는 함수를 선언합니다. 이 유형에 대한 함수 포인터를 만들려면 이제 다음을 수행 할 수 있습니다.

void dosomething() { }

functiontype func = &dosomething;
func();

int를 반환하고 char을 취하는 함수의 경우

typedef int (*functiontype2)(char);

그리고 그것을 사용

int dosomethingwithchar(char a) { return 1; }

functiontype2 func2 = &dosomethingwithchar
int result = func2('a');

함수 포인터를 읽기 좋은 형식으로 바꾸는 데 도움이되는 라이브러리가 있습니다. 부스트 기능 라이브러리는 위대하고 잘 노력 가치가 있습니다!

boost::function<int (char a)> functiontype2;

위의 것보다 훨씬 좋습니다.


C ++ 11부터 기능 라이브러리사용하여 간결하고 일반적인 방식으로이를 수행 할 수 있습니다 . 구문은 다음과 같습니다.

std::function<bool (int)>

여기서는 bool첫 번째 인수가 유형 인 단일 인수 함수의 반환 유형 int입니다.

아래에 예제 프로그램이 포함되어 있습니다.

// g++ test.cpp --std=c++11
#include <functional>

double Combiner(double a, double b, std::function<double (double,double)> func){
  return func(a,b);
}

double Add(double a, double b){
  return a+b;
}

double Mult(double a, double b){
  return a*b;
}

int main(){
  Combiner(12,13,Add);
  Combiner(12,13,Mult);
}

하지만 때로는 템플릿 함수를 사용하는 것이 더 편리합니다.

// g++ test.cpp --std=c++11

template<class T>
double Combiner(double a, double b, T func){
  return func(a,b);
}

double Add(double a, double b){
  return a+b;
}

double Mult(double a, double b){
  return a*b;
}

int main(){
  Combiner(12,13,Add);
  Combiner(12,13,Mult);
}

합격 다른 함수 매개 변수 함수의 주소를 아래와 같이

#include <stdio.h>

void print();
void execute(void());

int main()
{
    execute(print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void f()) // receive address of print
{
    f();
}

또한 함수 포인터를 사용하여 함수 를 매개 변수로 전달할 수 있습니다.

#include <stdio.h>

void print();
void execute(void (*f)());

int main()
{
    execute(&print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void (*f)()) // receive address of print
{
    f();
}

함수 포인터 를 전달해야합니다 . 구문은 약간 번거롭지 만 익숙해지면 정말 강력합니다.


Functions can be "passed" as function pointers, as per 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:

void foo(int bar(int, int));

is equivalent to this:

void foo(int (*bar)(int, int));

It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.

#include <stdio.h>

int IncMultInt(int a, int b)
{
    a++;
    return a * b;
}

int main(int argc, char *argv[])

{
    int a = 5;
    int b = 7;

    printf("%d * %d = %d\n", a, b, IncMultInt(a, b));

    b = 9;

    // Create some local code with it's own local variable
    printf("%d * %d = %d\n", a, b,  ( { int _a = a+1; _a * b; } ) );

    return 0;
}

참고URL : https://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c

반응형