没有宏的双链表的Foreach?

时间:2014-07-08 10:10:20

标签: c macros c-preprocessor

我正在使用double linked list并希望优化其使用情况。 我有很多地方迭代抛出所有列表元素。我想使用以下定义:

//
// Iterates through all protected files
//
#define FOR_EACH_PROTECTED_FILE_START(protectedFile) \
    for(PLIST_ENTRY protectedFileEntry = filterData.ProtectedFilesHead.Flink; protectedFileEntry != &filterData.ProtectedFilesHead; protectedFileEntry = protectedFileEntry->Flink) { \
    protectedFile = CONTAINING_RECORD(protectedFileEntry, MY_PROTECTED_FILE_TYPE, EntryLink);


#define FOR_EACH_PROTECTED_FILE_END }

有没有办法在没有宏的情况下做这个(宏是邪恶的bla..bla.bla)不要把这个结构放在我想要迭代foreach文件的每个地方?

你觉得这种风格怎么样?

2 个答案:

答案 0 :(得分:1)

您可以将样板逻辑移动到一个函数中,该函数控制循环并返回状态。

inline int iterate_protected_files(ProtectedFile_t* current, /*other state data*/)
{
  /* Bolierplate stuff to get next file*/
  *current = whatever;
  return current_exists;
}

...

while (iterate_protected_files(&protectedFile))
{
  /* do stuff with a protected file */
}

答案 1 :(得分:1)

你可以坚持使用宏,但是避免使用宏本身的大括号:

#define FOR_EACH_PROTECTED_FILE(protectedFile) \
    for( \
        PLIST_ENTRY protectedFileEntry = filterData.ProtectedFilesHead.Flink, \
        protectedFile = CONTAINING_RECORD(protectedFileEntry, MY_PROTECTED_FILE_TYPE, EntryLink); \
        protectedFileEntry != &filterData.ProtectedFilesHead; \
        protectedFileEntry = protectedFileEntry->Flink, \
        protectedFile = CONTAINING_RECORD(protectedFileEntry, MY_PROTECTED_FILE_TYPE, EntryLink) \
    )

像for(就像它实际上一样)使用它:

...
FOR_EACH_PROTECTED_FILE(protectedFile) {
    <code that deals with protectedFile>
}