-4

I want to check how this p?p->next:0 works. Its not the same operator as in java? Replacement, one liner for "if"?

e.g.

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

Joe C
  • 15,324
  • 8
  • 38
  • 50
ERJAN
  • 23,696
  • 23
  • 72
  • 146

2 Answers2

2

In C, 0 is false, everything else is true. The ternary operator used here is shorthand for

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

where if(p) is true for any value of p != 0. My preference when dealing with pointers is to compare againstNULL instead of 0, if (p != NULL){ ... }, but it's not uncommon to see 0 used. On every system I've worked on, NULL is 0, but I don't think that's mandated in the standard..? Someone here will know.

Jongware
  • 22,200
  • 8
  • 54
  • 100
yano
  • 4,827
  • 2
  • 23
  • 35
  • `p` is a pointer, not an integer – paddy Nov 08 '18 at 22:40
  • 1
    @paddy correct. There's plenty of `c` code that checks pointers this way. – yano Nov 08 '18 at 22:44
  • 1
    `NULL` is required to be a null pointer constant. Literal `0` is also a null pointer constant. They are not necessarily identical (`NULL` might expand to `(void *)0`, for example), but they can be used interchangeably as null pointers, and they compare equal to each other and to all other null pointers. – John Bollinger Nov 08 '18 at 23:21
  • @JohnBollinger thanks for the info/clarification. – yano Nov 08 '18 at 23:24
  • @usr2564301 even though you won't be notified... fair enough. Better complain to SO, looks like all their language tags have been code-ticked. – yano Nov 08 '18 at 23:26
  • @yano: post editors *do* get notified :) Code ticking things that are clearly `not` code is an annoying habit, `and` personally, I edit it out whenever I see it. There are a *lot* of broken posts on SO – alas, it appears not everyone is interested in maintaining a reasonably high level of quality. – Jongware Nov 09 '18 at 09:22
  • 1
    @usr2564301 ahhh, your name didn't autocomplete when I started typing it, so I didn't think you'd get notified. I guess I get a certain satisfaction when the language name I type matches what the code tag looks like, but you're right it's not code, I'll try to remember to stop doing it. – yano Nov 09 '18 at 14:51
1

NULL pointer is nothing but (void*) 0, so q = p?p->next:0; expands to

if (p != NULL)
    q = p->next;
else
    q = NULL;
Morpheus
  • 377
  • 2
  • 9