gpt4 book ai didi

c - 程序执行流程替代 switch(){...} 语句

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:38 25 4
gpt4 key购买 nike

我正在尝试实现一个具有以下功能的程序。

An SPI-Master sends 3 bytes of data to an SPI-Slave. For certain value of these data bytes, certain functions are to be called. For example FF FF FF calls the function A, FF FF FE calls the function B, and so on.

一个可能的解决方案可能是使用 switch case 语句,但是切换每个可能的 case 会太长。还有其他方法吗?

例如,最后一个数据字节必须设置 PWM 占空比。

10 = 0000 1010
20 = 0001 0100
30 = 0001 1110
40 = 0010 1000
50 = 0011 0010
60 = 0011 1100
70 = 0100 0110
80 = 0101 0000
90 = 0101 1010

从设备接收最后一个字节,对于这些情况中的每一种,它都必须设置占空比。第二个字节决定预分频器。例如:

0000 00001 0000 1010 sets the prescaler to 1 and duty cycle to 10
0000 00010 0000 1010 would set prescaler to 8 and duty cycle to 10

等等。

所以可能有很多不同的组合,处理所有可能情况的最佳方法是什么?

最佳答案

"...One possible solution might be using switch case statement, however switching each possible case would be too long. Is there any other way to do this?"

对于您正在自动化的流程所需的每个不同但必需的功能,您将需要恰好一个不同的方法(或方法系列)来完成它。 100 个不同的要求将需要实现 100 个不同的方法来满足这些要求。使用的构造取决于开发人员。状态机 ( such as a switch statement within a while loop ) 是一种常见的结构,通过许多不同的操作来控制执行流。如果使用此构造,可能需要 100 个 case: 部分。

如果出于某种原因不能接受 switch 语句,则不同的选项可能是函数指针数组。但是请注意,尽管此方法可能优于 switch/while 组合,但仍需要 独特功能 之间的 1:1 相关性:要求:

int op0(int b1, int b2, int b3);
int op1(int b1, int b2, int b3);
int op2(int b1, int b2, int b3);
int op3(int b1, int b2, int b3);
//.... and so on depending on how many operations needed

enum { // mnemonics with which to call array of function pointers.
OP0,
OP1,
OP2,
OP3,
....
};



int (*op[4]) (int b1, int b2, int b3);

int main(void) //or (int argc, char *argv[])
{
//initialize function pointer address to implementations:
op[0] = &op0;
op[1] = &op0;
op[2] = &op0;
op[3] = &op0;
// and so on for every operation needed
// other code in main
return 0;
}

int op0(int b1, int b2, int b3)
{
// code using b3 to set duty cycle
// ...
// code using b2 to set pre-scaler
// ...
// implement unique requirement of op0
return 0;
}

int op1(int b1, int b2, int b3)
{
// code using b3 to set duty cycle
// ...
// code using b2 to set pre-scaler
// ...
// implement unique requirement of op1
return 0;
}

/// and so on...

关于c - 程序执行流程替代 switch(){...} 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com