Menu
CoddyTech

Mutable Struct APIs

Lesson 25 of 48 in Coddy's C for Kotlin Developers course.

Kotlin methods have an implicit receiver, this, and a private set keeps code outside the class from writing a property. C uses explicit struct pointers and free functions; a header documents an API but does not create classes, methods or private fields, so any code holding the struct can write any member.

State-changing functions accept explicit struct pointers. Validate first so rejected operations preserve state. C has no implicit receiver and no exception like the one require throws; return a status instead.

Kotlin example

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 output:

3

C example

#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 output:

3
challenge icon

Challenge

Easy

Account contains integer balance. Implement withdraw(account,amount): return false without mutation for negative or unaffordable amounts; otherwise subtract and return true. Zero is valid. Input is balance and amount; output success:balance. Driver also probes independent accounts and rejection atomicity.

Edit the unlocked source and header files. Keep the declared public API compatible with the visible locked main.c, which calls it directly. Do not add another main. All numeric task fixtures are small enough to avoid overflow unless the task explicitly checks a range. Print only the specified output; the driver supplies input parsing and output when shown.

Try it yourself

#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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C for Kotlin Developers

Practice on your own: Online C compiler