首页 > 解决方案 > C:围绕没有其他操作数的变量的括号

问题描述

我正在研究 FreeRTOS 的源代码。我找到了这个片段: https ://github.com/TheKK/myFreeRTOS/blob/master/include/list.h#L268

#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList )                                        \
{                                                                                           \
    List_t * const pxConstList = ( pxList );                                                \
    /* Increment the index to the next item and return the item, ensuring */                \
    /* we don't return the marker used at the end of the list.  */                          \
    ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext;                            \
    if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) )  \
    {                                                                                       \
        ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext;                        \
    }                                                                                       \
    ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner;                                          \
}

我知道这( pxConstList )->pxIndex意味着访问指针变量 pxConstList 的数据。但我想知道 是什么意思surround a variable with parenthesis only

那是:

List_t * const pxConstList = ( pxList );
                             ~~~~~~~~~~

( pxTCB ) = ( pxConstList )->pxIndex->pvOwner;
~~~~~~~~~~

谢谢。

标签: cfreertos

解决方案


这些变量实际上是宏的参数。括号是必要的,因为一个参数可能是一个表达式,如果没有它们,它就不能正确地适应上下文。

例如考虑这个宏:

#define SQUARE(x) x*x

如果你这样调用这个宏:

SQUARE(4+5)

你会得到:

4+5*4+5

因为*具有比 更高的优先级+,这将评估为 29 而不是预期的 81。如果宏定义如下:

#define SQUARE(x) (x)*(x)

然后上面将扩展为:

(4+5)*(4+5)

这将评估为 81。

总而言之,建议始终将宏参数括起来以避免这些类型的问题。


推荐阅读