Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中定义常量之间的依赖关系?_C_Constants - Fatal编程技术网

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

C中定义常量之间的依赖关系?,c,constants,C,Constants,我对以下代码和常量使用了#define命令。我在第一行工作负载_MAX中定义了4,在第二行任务_COUNT_MAX中定义了10,并在第三行中使用了它们的乘法 经过长时间的调试,我意识到在执行代码时正确的值并不适用,我必须手动设置我不喜欢的值。(如第四行的40) 有人可以帮忙。 多谢各位 #define WORKLOAD_MAX 4 #define TASK_COUNT_MAX 10 #define READY_LOOP_DEEP TASK_COUNT_MAX*WORKLOAD_MAX //#de

我对以下代码和常量使用了#define命令。我在第一行工作负载_MAX中定义了4,在第二行任务_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;
}

宏是文本替换,其语义依赖于上下文。在这种情况下,
READY\u LOOP\u 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) ;

将按照您的预期进行评估。

您如何使用它们?非常感谢@Clifford。现在可以了。