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

Mah*_*Mah 3 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;
}
Run Code Online (Sandbox Code Playgroud)

Cli*_*ord 5

宏是文本替换,其语义依赖于上下文.在这种情况下出现的任何READY_LOOP_DEEP将被替换为4*10这方面可能不会像你想象的由于运算符优先级和评估顺序.这是一个危险的宏的例子,应该这样写:

#define READY_LOOP_DEEP (TASK_COUNT_MAX * WORKLOAD_MAX)
Run Code Online (Sandbox Code Playgroud)

用括号确保评估顺序符合预期.

在你的情况下表达式:

readyQueueHead = (readyQueueHead + 1) % READY_LOOP_DEEP;
Run Code Online (Sandbox Code Playgroud)

扩展为:

readyQueueHead = (readyQueueHead + 1) % 4 * 10 ;
Run Code Online (Sandbox Code Playgroud)

从左到右的评估,所以(readyQueueHead + 1) % 4乘以10,而不是(readyQueueHead + 1) % 40你想要的.

括号将表达式更改为:

readyQueueHead = (readyQueueHead + 1) % (4 * 10) ;
Run Code Online (Sandbox Code Playgroud)

它将根据您的意图进行评估.