c - 优化 C 中计数器的一段幼稚代码。需要更好的解决方案

标签 c

我在代码中为系统中的一个进程使用了​​三个计数器 c1、c2 和 c3。在某些点,我需要触发每个计数器并在特定点(targetc1、targetc2、targetc3)结束它。因此,我使用三个标志 cf1、cf2 和 cf3 来检查每当触发我的进程时计数器标志是否设置为 ON,然后检查计数器目标是否到达终点。除了使用三个标志之外,还有更好的方法吗?将来我可能需要在代码中使用更多计数器,但我认为它不应超过 6 个计数器。 下面给出了 p1 进程的代码片段来解释我的问题。

/*P1 process variables*/
static int c1,c2,c3;
static int targetc1,targetc2,targetc3;
static int cf1,cf2,cf3;

p1startingfunction()
{
    int a;
    if(cf1 == 1)
    {
    c1++;
    if(c1==targetc1)
        /*counter reached do something*/
        c1trigger();
    }
    if(cf2 == 1)
    {
    c2++;
    if(c2==targetc2)
        /*counter reached do something*/
        c2trigger();
    }
   if(cf3 == 1)
    {
    c3++;
    if(c3==targetc3)
        /*counter reached do something*/
        c3trigger();
    }
}

最佳答案

这方面仍有很大的改进空间,但这个答案专门用于最大限度地减少代码重复。

话虽如此,您可以使用数组:

/*P1 process variables*/
static int c[3];
static int targetc[3];
static int cf[3];
static void (*ctrigger[3])(void);

p1startingfunction()
{
    int a, i;
    for (i = 0; i < 3; i++) {
        if (cf[i] == 1) {
            c[i]++;
            if (c[i] == targetc[i]) {

                /* counter reached do something */
                ctrigger[i]();                    
            }
        }
    } 
}

或者你可以使用一个看起来像这样的结构:

struct counter {
    int c;
    int target;
    int f;
    void (*trigger)(void);
};

然后创建一个结构数组。

struct counter counters[3];

关于c - 优化 C 中计数器的一段幼稚代码。需要更好的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20104347/

相关文章:

想要c指针解释

c - 如何利用 sizeof() 返回 malloc 缓冲区分配的大小

arrays - C 结构体可以包含指向其他结构体数组的指针(具有不同的长度)

在 C 中创建大型数组

c - 使用项目时turbo c中的配置文件无效

c - 套接字编程头文件中使用的一段代码的解释

c - GCC 为什么以及如何编译缺少 return 语句的函数?

c - 在循环中使用定义(c 编码)

c - 我对 SPOJ 的解决方案中的段错误 - 下一个回文

c - 为什么我必须显式链接 libm?