samedi 21 novembre 2020

How can I write the "?:" statements without using the '?' (question mark)?

node1 and node2 are nodes of a linked list.

Node* node1, Node* node2;
int carry = 0;
int sum;
sum = carry + (node1 ? node1->data : 0) + (node2 ? node2->data : 0);

Since x ? y : z works like if(x) y else z I tried

if (node1 && node2)
 sum = carry + node1->data + node2->data;
else if(node1 && !node2)
 sum = carry + node1->data;
else if(!node1 && node2)
 sum = carry + node2->data;
else if(!node1 && !node2)
 sum = carry;

Can we use nodes as if they were booleans like this? If not, how can I write this statement without using the question mark?

Aucun commentaire:

Enregistrer un commentaire