Conditional operator with a constant (true) value?

后端 未结 2 1401
醉话见心
醉话见心 2021-02-02 09:28

I was looking at some preprocessor macros used in OpenSSL, and I came across the following from crypto/stack/safestack.h:

#define CHECKED_STACK_OF(t         


        
相关标签:
2条回答
  • 2021-02-02 10:05

    It's a static assertion about the function type before the cast, providing a type-safe cast.

    From C11 (n1570) 6.5.15 (from the constraints section)

    Conditional operator

    (3) One of the following shall hold for the second and third operands:

    • [omitted non-pointer stuff]
    • both operands are pointers to qualified or unqualified versions of compatible types;
    • one operand is a pointer and the other is a null pointer constant; or
    • one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void.

    The third operand is a pointer to a function (so the last bullet never applies), so this compiles (without a warning) only if either p is a null pointer constant or of a type compatible with void (*)(type) for the last macro (after conversion to a function pointer, if p is a function designator).

    0 讨论(0)
  • 2021-02-02 10:16

    It's code that double checks if the correct type is passed. The pointer p is passed and along the type of that pointer must be also manually typed in the macro.

    The ternary expression will always return the second operand but both second and third operands will be checked if their type matches, and if they don't you should get a compiler error.

    A simple example:

    int* p = NULL ;
    
    1 ? p : ( float* )p ;    //error
    
    1 ? p : ( int* )p ;      //ok
    
    0 讨论(0)
提交回复
热议问题