首页 > 解决方案 > 这个 C 代码片段中的“p?p->next:0”是什么,我该如何运行它?

问题描述

我想检查这个 p?p->next:0 是如何工作的。它与java中的运算符不同吗?替换,“如果”的一个衬里?

例如

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主要

标签: c

解决方案


在 C 中,0 是false,其他一切都是true。这里使用的三元运算符是

if (p)
{
  q = p->next;
}
else
{
  q = 0;
}

if(p)对于 的任何值,哪里都为真p != 0。在处理指针时,我的偏好是比较NULL而不是 0, if (p != NULL){ ... },但看到使用 0 的情况并不少见。在我工作过的每个系统上,NULL都是 0,但我不认为这是标准中规定的..?这里有人会知道的。


推荐阅读