Why so many parentheses in SUCCEEDED macro?

2019-06-20 05:18发布

Windows SDK features SUCCEEDED macro:

#define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0)
-----------------------^-------------^-----

clearly as with other macros there're parentheses to ensure right interpretation of the intent by compiler.

What I don't get is why there are parentheses around (HRESULT)(hr) (I marked them with ^ character). hr is parenthesized so that some complex construct can be there, HRESULT is parenthesized to form a C-style cast, then the whole >= construct is parenthesized as well, so why the extra pair of parentheses around (HRESULT)(hr)?

8条回答
倾城 Initia
2楼-- · 2019-06-20 06:03

The C standard puts the cast at a higher precedence than the comparison, so the parens are not required for the complier.

However, people read the macro definition, and putting them in makes the precedence explicit, so that it is obvious to people reading it that it is the result of comparing ((HRESULT)hr) with zero rather than casting the result of the comparison without having to think about the precedence.

查看更多
老娘就宠你
3楼-- · 2019-06-20 06:15

Short answer: who knows what the MS developers were thinking. However, the parentheses around hr is obviously necessary since hr could be an expression consisting of more than a single operand. The parentheses around ((HRESULT)(hr)) is unnecessary as far as I can see. This was probably just done out of a cautionary habit: when working with the preprocessor, it's better to have too many parentheses than too few.

查看更多
登录 后发表回答