Menu
CoddyTech

変更可能な構造体API

Coddyの「Luau開発者のためのC」コースのレッスン 25/48。

コロンで定義されたLuauのメソッドは暗黙的なselfを受け取り、account:withdraw(2)はテーブルを自動的に渡します。Cの関数は構造体へのポインターを明示的に受け取り、->で更新します。メソッド、メタテーブル、クラスシステムは関与しません。状態は構造体ごとに割り当て、拒否された操作ではその状態を保持します。

Luau

local account = {balance = 5}
function account:withdraw(amount)
    self.balance -= amount
end
account:withdraw(2)
print(account.balance)

C17

#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;};
static void withdraw(struct Account *self,int amount){self->balance-=amount;}
int main(void) {
struct Account a={5};withdraw(&a,2);printf("%d\n",a.balance);
return 0;
}

移植のルール

構造体の状態を変更する前に、操作を検証します。

challenge icon

チャレンジ

簡単

Accountには整数のbalanceが含まれています。withdraw(account,amount)を実装してください。amountが負または残高不足の場合は、変更を加えずにfalseを返し、それ以外の場合は差し引いてtrueを返します。0は有効です。入力はbalanceとamountで、出力は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腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Luau開発者のためのCのすべてのレッスン

自分で練習してみよう: Cオンラインコンパイラ