首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >程序执行流替代switch(){.}语句

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

Stack Overflow用户
提问于 2019-10-28 11:41:55
回答 2查看 82关注 0票数 0

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

,Slave将3字节的数据发送给SPI-从服务器.对于这些数据字节的某些值,将调用某些函数。例如,FF FF FF调用函数AFF FF FE调用函数B,依此类推。

一个可能的解决方案可能是使用switching语句,但是切换每个可能的情况会太长。还有别的办法吗?

例如,最后一个数据字节必须设置PWM荷兰周期。

代码语言:javascript
复制
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将预分频器设置为1,将占空比设置为10

0000 00010 0000 1010会将预分频器设置为8,将占空比设置为10

诸若此类。

因此,有许多不同的组合可能,什么是最好的方式来处理所有可能的案件?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-28 13:01:42

"...One可能的解决方案可能是使用开关case语句,但是切换每个可能的情况会太长。还有其他方法吗?“

对于自动化过程所需的每个不同但必需的功能,您将需要一种完全不同的方法(或一系列方法)来完成它。100项不同的要求将需要100种不同的方法来满足要求。所使用的构造由开发人员决定。状态机( State, )是通过许多不同的操作来控制执行流的常见构造。如果使用此构造,则可能需要100个case:部分。

如果由于任何原因,开关语句不可接受,则不同的选项可能是一个函数指针数组。不过,请注意,这种方法虽然比switch/while组合更可取,但仍然需要唯一函数:需求之间的1:1相关性。

代码语言:javascript
复制
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...
票数 1
EN

Stack Overflow用户

发布于 2019-10-28 11:46:26

简单

逐字节读取。如果第一个字节是0xff,则输入特定状态。如果下一个字节也是0xff,那么输入另一个状态。如果下一个字节是0xff,那么调用函数A,如果是0xfe调用函数B等,在第三个字节之后,返回到原来的起始状态。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58590307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档