0

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?

1
  • auto data = [](Node* p, int default_value) { if (p) return p->data; return default_value; }; then use int sum = carry + data(node1, 0) + data(node2, 0);
    – Eljay
    Commented Nov 21, 2020 at 14:52

1 Answer 1

1

That ? : is called the conditional operator (or sometimes ternary operator in the context of C-like languages). In C++ x ? y : z works exactly like if (x) y else z except that the if else block isn't an expression and doesn't return a value. So if you can use node ? then you can use if (node), any numeric expressions can be converted into a boolean expression

However you don't actually to combine the 2 ternary expression and need so many if blocks like that. Just do like how the ternary expression is evaluated

sum = carry
if (node1)
    sum += node1->data;
if (node2)
    sum += node2->data;
5
  • 2
    actually it is the conditional operator. A ternary operator is any operator that takes 3 operands and coincidentally C++ has only one of this kind, but in principle there could be others Commented Nov 21, 2020 at 12:36
  • its also not "exactly" like the if, because it evaluates to the common type of the 2nd and 3rd operator, but thats a simplification that is probably ok in this context Commented Nov 21, 2020 at 12:40
  • 2
    @idclev463035818 For more pedantry, it's certainly true that it "is called" the ternary operator, by many people.
    – aschepler
    Commented Nov 21, 2020 at 14:41
  • 1
    @aschepler haha, I had the same thoughts, but nitpicking my own nitpick seemed too pathetic ;). I'd add "colloquially", then I am fine with it Commented Nov 21, 2020 at 14:42
  • Example for which if…else and ? : differ: Given struct Blargh { Blargh(int x) { std::cout << "Blargh!\n"; } };, 0 ? Blargh(0) : 0; prints “Blargh!” but if (0) Blargh(0); else 0; does not. Commented Dec 17, 2020 at 1:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.