상태형 정책 구성
Coddy의 Swift 개발자를 위한 C 코스 레슨. 48개 중 40번째.
Swift 클로저는 자신이 사용하는 변수를 캡처하며, ARC는 클로저가 살아 있는 동안 캡처된 상태를 유지합니다. 클로저를 만든 함수에서 빠져나온 뒤에도 마찬가지입니다. C의 콜백과 컨텍스트 쌍에는 이런 동작이 포함되어 있지 않습니다. void * 컨텍스트는 단순한 주소이므로, 이 주소가 유효한 상태로 유지되는 기간을 정의하고 모든 호출에서 계속 유효하게 유지한 뒤, 제공된 함수를 해당 주소와 함께 호출해야 합니다.
상태를 가진 동작을 전달하려면 컨텍스트 포인터와 함수 포인터를 한 쌍으로 사용하세요. 컨텍스트는 호출이 이루어질 때마다 계속 유효한 상태여야 합니다.
Swift 예시
let factor = 3
let policy = { (n: Int) in factor * n }
print(policy(4))
Swift 출력:
12C 예시
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
struct Policy {void *context;int (*apply)(void*,int);};
static int multiply(void *context,int n){return *(int*)context*n;}
int main(void) {
int factor=3;struct Policy p={&factor,multiply};printf("%d\n",p.apply(p.context,4));
return 0;
}
C 출력:
12챌린지
쉬움Policy는 context와 apply(context,value)를 저장합니다. 제공된 콜백을 동일한 context로 한 번 호출하여 price_with(policy,value)를 구현하세요. 입력은 factor와 value입니다. 드라이버는 offset 정책도 제공하고 호출 횟수를 확인하므로, 곱셈을 하드 코딩하는 것만으로는 충분하지 않습니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 표시된 잠금된 main.c에서 직접 호출하므로 선언된 공개 API와 호환되도록 하세요. main을 추가하지 마세요. 범위를 명시적으로 확인하는 작업이 아니라면 모든 숫자 작업 입력값은 오버플로가 발생하지 않을 만큼 작습니다. 지정된 출력만 출력하세요. 입력 구문 분석과 출력이 표시된 경우 드라이버가 이를 처리합니다.
직접 해보기
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
static int multiply(void *context,int n){return *(int*)context*n;}
typedef struct {int offset,calls;} Counter;
static int shifted(void *context,int n){Counter *p=context;p->calls++;return n+p->offset;}
int main(void){int factor,value;if(scanf("%d%d",&factor,&value)!=2)return 1;Counter c={7,0};if(price_with((Policy){&c,shifted},3)!=10 || c.calls!=1)return 3;printf("%d\n",price_with((Policy){&factor,multiply},value));return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Swift 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러