Control-Conditionals

博客介绍了编写if语句和case语句的准则。编写if语句时,要先写正常路径代码、确保分支正确等;编写case语句时,要按字母或数字顺序排序、将正常情况放首位等,还给出了避免错误和简化代码的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Guidelines when writing if statements
1. Write the nominal path through the code first; then write the unusual cases.
2. Make sure that you branch correctly on equality.
3. Follow the if clause with a meaningful statement.
4. Conside the else clause.
5. Test the else clause for correctness.
6. Check for revseal of the if and else clauses.
7. Simplify complicated tests with boolean function calls.
8. Put the most common cases first.
9. Make sure that all cases are covered.
10. Replace if-then-else chains with other constructs if your language supports them.

Case statement
1. Order casesalphabetically or numerically if they are equally important.
2. Put the normal case first.
3. Order cases by frequency.
4. Keep the actions of each case simple.
5. Don't make up phony variables in order to be able to use the case statment.
6. Use the default clause only to detect legitimate defaults.
7. Use the default clause to detect errors.
8. In C++ and Java, avoid dropping through the end of a case statement.

#include "motor_control.h" #include "headfile.h" static uint8_t duty; void motor_init(void) { // 初始化PWM频率为50Hz,占空比初始值 pwm_init(PWMB_CH4_P77, 50, 600); pwm_init(PWMB_CH1_P74, 50, 600); pwm_init(PWMA_CH3P_P64, 50, 600); pwm_init(PWMA_CH1P_P60, 50, 600); } void motor_set_duty(uint8_t duty) { // 设置电机占空比 pwm_duty(PWMB_CH4_P77, duty); pwm_duty(PWMB_CH1_P74, duty); pwm_duty(PWMA_CH3P_P64, duty); pwm_duty(PWMA_CH1P_P60, duty); }Build target 'STC32G12K128' compiling main.c... ..\USER\src\main.c(36): warning C140: 'motor_init' undefined; assuming 'extern int motor_init()' ..\USER\src\main.c(43): error C25: syntax error near 'motor_duty' ..\USER\src\main.c(46): warning C140: 'motor_set_duty' undefined; assuming 'extern int motor_set_duty()' ..\USER\src\main.c(46): warning C95: 'motor_set_duty': too many actual parameters ..\USER\src\main.c(49): error C316: unterminated conditionals ..\USER\src\main.c(49): error C25: syntax error near '<EOF>' ..\USER\src\main.c(49): error C7: compilation aborted compiling motor_control.c... ..\CODE\motor_control.c(3): warning C34: 'duty': missing declaration specifiers ..\CODE\motor_control.c(3): error C42: 'duty': not in formal parameter list ..\CODE\motor_control.c(5): error C42: 'motor_init': not in formal parameter list ..\CODE\motor_control.c(5): error C25: syntax error near '{' ..\CODE\motor_control.c(20): error C316: unterminated conditionals ..\CODE\motor_control.c(20): error C7: compilation aborted Target not created. Build Time Elapsed: 00:00:00
最新发布
07-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值