问题描述
我遇到了这个问题-
为什么结果: 1? (int *)0:(void *)0
与以下结果不同:
1吗? (int *)0:(void *)1
有何不同?应该是 0
或(int *)0
。
如何检查结果?
在哪里可以使用这种类型的表达式?
How it is differ ? It should be 0
or (int*)0
.
How to check the result ?
Where we can use such type of expression ?
推荐答案
唯一的区别在于类型:第一个一个返回一个 int *
,第二个返回一个 void *
。
The only difference is in types: the first one returns an int *
, the second one returns a void *
.
根据C11标准,第6.5.15节条件运算符,¶6:
From C11 standard, §6.5.15 Conditional operator, ¶6:
(强调我的意思)
请记住,指向非 void
的指针不能是空指针常量,但只有一个 null指针。 C11§6.3.2.3指针,¶3:
Remember that a pointer to non-void
cannot be a null pointer constant but just a null pointer. C11 §6.3.2.3 Pointers, ¶3:
因此,在这里:
1 ? (int *) 0 : (void *) 0
(int *)0
只是一个 null指针,而(void *)0
是一个 null指针常量,因此结果的类型为 int *
( 如果一个操作数为空指针常量,则结果为另一操作数的类型)。
(int *) 0
is just a null pointer while (void *) 0
is a null pointer constant, so the result has type int *
("if one operand is a null pointer constant, the result has the type of the other operand").
在这里:
1 ? (int *) 0 : (void *) 1
没有空指针常量(只有一个 null指针,第一个),因此结果的复合类型为 void *
(如果两个操作数都是指针,则为指向兼容类型或兼容类型的不同限定版本,结果类型是指向复合类型的适当限定版本的指针。
there are no null pointer constants (only a null pointer, the first one), so the result has the composite type void *
("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").
类型,但它们都是 null指针。还要注意,结果是从不 0
,就像您在问题中说的那样,它始终是指针。
The results have different types but they are both null pointers. Also note that the result is never 0
as you say in your question, it's always a pointer.
不幸的是,没有标准的方法可以看到C的差异,C ++对它有所支持( typeinfo
),但是结果却有所不同。
Unfortunately there is no standard way to see the difference in C, C++ has some support about it (typeinfo
) but results are different there.
我想不出一个有用而具体的用法语言的晦涩之处。
I can't think about a useful and concrete use of this obscure corner of the language.
这篇关于三元运算符和类型转换的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!