Menu
CoddyTech

可变结构体 API

Coddy 面向 Ruby 开发者的 C 课程的第 25 课,共 48 课。

Ruby 方法会通过 self 隐式找到接收者,而像 account.balance -= 2 这样的属性写入器会就地更新对象。C 函数可以接收结构体指针,并通过 -> 更新它,但接收者是显式参数,而且不涉及类系统。为每个结构体分配状态,并在操作被拒绝时保留该状态。

Ruby

Account = Struct.new(:balance)
account = Account.new(5)
account.balance -= 2
puts 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;};
int main(void) {
struct Account a={5};struct Account *p=&a;p->balance-=2;printf("%d\n",a.balance);
return 0;
}

移植规则

更改结构体状态之前,先验证操作。

challenge icon

挑战

简单

Account 包含整数余额。实现 withdraw(account,amount):如果金额为负数或余额不足,返回 false 且不修改账户;否则扣除金额并返回 true。金额为 0 也是有效的。输入为余额和金额;输出为 success:balance。驱动程序还会测试相互独立的账户以及拒绝操作的原子性。

编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,该文件会直接调用它。不要添加另一个 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自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Ruby 开发者的 C中的所有课

自己练习: C 在线编译器