Menu
CoddyTech

변경 가능한 구조체 API

Coddy의 Kotlin 개발자를 위한 C 코스 레슨. 48개 중 25번째.

Kotlin 메서드에는 암시적 수신자인 this가 있으며, private set은 클래스 외부의 코드가 속성에 값을 쓰지 못하게 합니다. C는 명시적인 구조체 포인터와 독립 함수를 사용합니다. 헤더는 API를 문서화하지만 클래스, 메서드 또는 비공개 필드를 만들지는 않으므로 구조체를 가지고 있는 코드는 모든 멤버에 값을 쓸 수 있습니다.

상태를 변경하는 함수는 명시적인 구조체 포인터를 받습니다. 먼저 유효성을 검사하여 거부된 작업이 상태를 그대로 유지하도록 하세요. C에는 암시적 수신자도 require가 던지는 예외와 같은 것도 없으므로, 대신 상태를 반환하세요.

Kotlin 예제

class Account(balance: Int) {
    var balance = balance
        private set

    fun spend(n: Int) {
        require(n <= balance) { "insufficient funds" }
        balance -= n
    }
}

fun main() {
    val a = Account(5)
    a.spend(2)
    println(a.balance)
}

Kotlin 출력:

3

C 예제

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
struct Account {int balance;};
int main(void) {
struct Account a={5};struct Account *p=&a;p->balance-=2;printf("%d\n",a.balance);
return 0;
}

C 출력:

3
challenge icon

챌린지

쉬움

Account에는 정수 balance가 들어 있습니다. withdraw(account,amount)를 구현하세요. 음수이거나 잔액이 부족한 금액이면 상태를 변경하지 않고 false를 반환하고, 그렇지 않으면 금액을 빼고 true를 반환하세요. 0은 유효합니다. 입력은 잔액과 금액이고, 출력은 success:balance입니다. 드라이버는 독립된 계정과 거부 시 원자성도 확인합니다.

잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 직접 호출하는 잠긴 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"
int main(void){Account a;int amount;if(scanf("%d%d",&a.balance,&amount)!=2)return 1;Account x={4},y={9};if(withdraw(&x,5)||x.balance!=4||withdraw(&x,-1)||x.balance!=4||!withdraw(&x,2)||x.balance!=2||y.balance!=9)return 2;int ok=withdraw(&a,amount);printf("%d:%d\n",ok,a.balance);return 0;}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Kotlin 개발자를 위한 C의 모든 레슨

직접 연습해 보세요: 온라인 C 컴파일러