Conditional operator with a constant (true) value?

空扰寡人 提交于 2019-12-02 20:19:30

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

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!