c - 比 if-else if 更好的解决方案?

标签 c embedded

我必须根据像 83025(>65535)这样的大数字的值来做一些事情。为此,我不能使用 switch-case,因为它仅使用最大值为 255 的整数参数。(或者至少我是这样知道的。不过,我仍然尝试并编译了它,但 switch-case 效果不佳。 )

所以我想我应该制作一个像下面这样的 if-else if 梯子,但它看起来不太优雅。

if      ((refnum == 32120) ||  
         (refnum == 32075))   {

else if  (refnum == 51036)    {

else if ((refnum == 61024) ||  
         (refnum == 61060))   {

else if ((refnum == 71030) ||  
         (refnum == 71048))   {

else if ((refnum == 72012) ||  
         (refnum == 72024) ||  
         (refnum == 72048))   {

else if ((refnum == 81025) ||  
         (refnum == 81050) ||  
         (refnum == 81100))   {

else if ((refnum == 82012) ||  
         (refnum == 82024) ||  
         (refnum == 82048) ||  
         (refnum == 82096))   {

else if ((refnum == 83050) ||  
         (refnum == 83100))   {

您能否确认这是执行此操作的正确方法?或者你有更好的主意吗?

其他信息:

  • 引用句柄是一个 32 位无符号整数

  • 大数字来自字符串的中间,strtol 将其转换为 DWORD

  • 在每种情况下我必须做的事情是执行strcpy,然后返回某个值。

  • 代码嵌入并在 16 位微 Controller 上运行

最佳答案

have to do some things based on the value of a big number like 83025

然后确保所有涉及的变量都使用uint32_t

For this I can't use switch-case since it uses only integral arguments of a max value of 255

这是一个误解,不知道你从哪里得到这个想法。 switch 语句适用于所有整型常量表达式。 switch 语句本身没有数字限制。

(事实上,如果 switch 语句的控制表达式恰好是较小的整数类型,它会隐式提升为 int 类型。)

So I thought I would make an if-else if ladder like this below but it seems not too elegant. Can you confirm that this is the proper way to do this? Or do you have a better idea?

if-else 可能会产生与相应开关完全相同的机器代码。该开关可能会增加一点可读性,因此可能是更好的选择:

switch (refnum)
{
  case 32120: do_this(); break;
  case 61024: do_that(); break;
  ...
  default:    do_something();
}
<小时/>

替代方案:

我注意到这些是按排序顺序排列的整数值。如果有很多值或者需要快速查找,您也可以用二分搜索替换整个内容。这可能会提供更快的代码,但也会增加复杂性。最好使用 C 标准 bsearch()

但是,如果您最终希望实现的是返回指向字符串的指针,那么此解决方案可能是理想的。然后,您可以将数字和字符串存储为键值对:

typedef struct
{
  uint32_t key;
  const char* str;
} thingie_t;

static const thingie_t things [] = 
{
  { 32120, "text string" },
  { 32075, "another text string" },
  ...
};
<小时/>

the big number comes from the middle of a string and strtol converts it to a DWORD

为什么使用有符号数字?数据似乎没有签名。什么是DWORD?这是 Windows 编程中的一些臭味类型,在嵌入式系统中绝对应该避免。使用 stdint.h 中的类型,而不是一些丑陋的自制类型。

关于c - 比 if-else if 更好的解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46805799/

相关文章:

c - 具有单个成员的结构是否具有与成员类型相同的性能?

c - 从 TCP 套接字 C 读取

C 中 printf 函数的代码

c - 这个空指针是怎么回事?

c - freertos 中的堆栈溢出

assembly - ARM架构中的GT和HI指令有什么区别?

c - 在嵌入式 C 中显示 "expected expression before while"

c - 如何在 C 中序列化和反序列化 Hessian 调用

c - PlatformIO 构建失败 : undefined reference to http_parser_init

c - ARM恩智浦LPC2378 : Is is safe to modify GPIO pin output state via register access?