【问题标题】:Dependency between defining constants in C? [duplicate]在 C 中定义常量之间的依赖关系? [复制]
【发布时间】:2018-06-18 15:55:45
【问题描述】:

我使用#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;
}

【问题讨论】:

  • 你如何使用它们?

标签: c constants


【解决方案1】:

宏是文本替换,其语义取决于上下文。在这种情况下,任何出现的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) ;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2014-02-25
    • 1970-01-01
    相关资源
    最近更新 更多