我想检查这个 p?p->next:0 是如何工作的。 它和java中的运算符不一样吗?替换,一个“if”的衬里?
例如
x = (5>6)? 10 : 4 ; //should assign x =4
struct node
{
int value;
struct node *next;
};
void rearrange(struct node *list)
{
struct node *p, * q;
int temp;
if ((!list) || !list->next)
return;
p = list;
q = list->next;
while(q)
{
temp = p->value;
p->value = q->value;
q->value = temp;
p = q->next;
q = p?p->next:0;
}
}
//int main
最佳答案
在 C 语言中,0 为 false
,其他均为 true
。这里使用的三元运算符是
if (p)
{
q = p->next;
}
else
{
q = 0;
}
其中 if(p)
对于任何 p != 0
值都为 true。在处理指针时,我的偏好是与 NULL
进行比较,而不是 0,if (p != NULL){ ... }
,但使用 0 的情况并不少见。在我工作过的每个系统上,NULL
都是 0,但我不认为这是标准中强制规定的……?这里有人会知道。
关于c - 此 C 代码片段中的 "p?p->next:0"是什么以及如何运行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53216921/