三元运算符和类型转换的混淆

标签 c type-conversion ternary-operator void-pointers

我已经完成了这个问题-

为什么结果是:1? (int *)0 : (void *)0
不同于以下结果: 1? (int *)0 : (void *)1

它有何不同?它应该是 0(int*)0
如何查看结果?
我们在哪里可以使用这种表达方式?

最佳答案

唯一的区别在于类型:第一个返回 int * , 第二个返回 void * .

来自 C11 标准,§6.5.15 条件运算符,¶6:

If both the second and third operands are pointers or one is a null pointer constant and the other is a pointer, the result type is a pointer to a type qualified with all the type qualifiers of the types referenced by both operands. Furthermore, if both operands are pointers to compatible types or to differently qualified versions of compatible types, the result type is a pointer to an appropriately qualified version of the composite type; if one operand is a null pointer constant, the result has the type of the other operand; otherwise, one operand is a pointer to void or a qualified version of void, in which case the result type is a pointer to an appropriately qualified version of void.

(强调我的)

请记住,指向非 void 的指针不能是一个空指针常量,而只是一个空指针。 C11 §6.3.2.3 指针,¶3:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

66) The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant; see 7.19.

所以,这里:

1 ? (int *) 0 : (void *) 0

(int *) 0只是一个空指针(void *) 0是一个空指针常量,所以结果的类型是int * (“如果一个操作数是空指针常量,则结果具有另一个操作数的类型”)。

在这里:

1 ? (int *) 0 : (void *) 1

没有空指针常量(只有一个空指针,第一个),所以结果是复合类型void * (“如果两个操作数都是指向兼容类型或兼容类型的不同限定版本的指针,则结果类型是指向复合类型的适当限定版本的指针”)。

结果有不同的类型,但它们都是空指针。另请注意,结果是从不 0正如您在问题中所说,它始终是一个指针。

不幸的是,没有标准的方法来查看 C 中的差异,C++ 对此有一些支持 (typeinfo),但结果是不同的。

Where we can use such type of expression?

我想不出该语言的这个晦涩角落的有用和具体用法。

关于三元运算符和类型转换的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14094060/

相关文章:

c - 如何在 Visual Studio 中使用优化器和分析器

c - C 字符串程序的输出

templates - 是否可以在 vhdl 中使用泛型类型?

我可以直接使用条件为C中的变量赋值吗

java - Java 1.4 中三元条件运算符的意外副作用

c - 在 gdb 中观察内存范围?

Ctags 作为创建标签文件的库

java - Spring StringToObject.toObject() 未在列表中调用?

c++ - 混淆克隆传递参数

java - Java If Else 语句的简写形式