C中定义常量之间的依赖关系?

时间:2018-06-18 15:55:45

标签: c constants

我使用#define命令来执行以下代码和常量。我在第一个WORKLOAD_MAX中定义了4和第二行TASK_COUNT_MAX和10,并在第三行中使用了它们。

经过长时间的调试后,我意识到执行代码时正确的值不适用,我必须手动设置我不喜欢的值。 (如第四条注释行中的40)

有人可以提供帮助。 谢谢

#define WORKLOAD_MAX 4
#define TASK_COUNT_MAX 10
#define READY_LOOP_DEEP TASK_COUNT_MAX*WORKLOAD_MAX
//#define READY_LOOP_DEEP 40

struct workItem                         // It is a STRUCT to keep the status of task in different stages
{
    int task_ID;                            // Task ID
    int workload_ID;                    // Workload ID
};

// Read from the beginning of the readyQueue
struct workItem readFromReadyQueue()
{
    struct workItem witem;
    // Picking up from queue head
    witem = readyQueue[readyQueueHead];
    // Move forward the queue head index in rotation
    readyQueueHead = (readyQueueHead + 1) % READY_LOOP_DEEP;
    // Reduce the number of queue elements
    readyQueueSize--;
    #ifdef PRINT_ReadReadyQueue
        printf("Task_ID #%d (Workload_ID #%d) read from readyQueue.\n", witem.task_ID , witem.workload_ID);
    #endif
    return witem;
}

1 个答案:

答案 0 :(得分:5)

宏是文本替换,其语义取决于上下文。在这种情况下,READY_LOOP_DEEP的任何出现都将替换为4*10,由于运算符优先级和评估顺序,上下文中的行为可能与您的预期不同。这是危险宏的一个例子,应该这样编写:

#define READY_LOOP_DEEP (TASK_COUNT_MAX * WORKLOAD_MAX)

带括号以确保评估顺序符合预期。

在你的情况下表达式:

readyQueueHead = (readyQueueHead + 1) % READY_LOOP_DEEP;

扩展为:

readyQueueHead = (readyQueueHead + 1) % 4 * 10 ;

使用从左到右的评估,因此(readyQueueHead + 1) % 4乘以10,而不是(readyQueueHead + 1) % 40,如您所愿。

括号将表达式更改为:

readyQueueHead = (readyQueueHead + 1) % (4 * 10) ;

将根据您的意愿进行评估。

相关问题