Menu
CoddyTech

可変な構造体のAPI

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

Dartのメソッドには暗黙のレシーバーthisがあり、アンダースコアで始まる名前はクラスではなくライブラリ内でのみ非公開です。Cにはメソッドがありません。状態を変更する操作は、明示的な構造体ポインターを受け取る自由関数であり、ヘッダーはAPIを文書化しますが、クラス、メソッド、非公開フィールドを作成するものではありません。

状態を変更する関数は、明示的な構造体ポインターを受け取ります。操作が拒否された場合に状態が保持されるよう、最初に検証します。Cには暗黙のレシーバーがありません。a->balanceは(*a).balanceの省略形です。

Dartの例

class Account {
  int balance;
  Account(this.balance);

  bool spend(int amount) {
    if (amount < 0 || amount > balance) return false;
    balance -= amount;
    return true;
  }
}

void main() {
  final account = Account(5);
  account.spend(2);
  account.spend(9);
  print(account.balance);
}

Dartの出力:

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;};
static bool account_spend(struct Account *a,int amount){
if(amount<0||amount>a->balance)return false;
a->balance-=amount;return true;
}
int main(void) {
struct Account account={5};account_spend(&account,2);account_spend(&account,9);printf("%d\n",account.balance);
return 0;
}

Cの出力:

3
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腕試し

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

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

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