Doubt with the ternary operator

Asked

Viewed 196 times

1

Which means the following expression:

struct Node *temp = root->left ? root->left : root->right;

I’m wondering if he’s checking the existence of the pointer root->left or comparing *temp with root->left, then it wouldn’t have to be "=="?

1 answer

2


This is similar to an if:

struct Node *temp = root->left ? root->left : root->right;

and would be equivalent to doing this:

struct Node *temp;

if (root->left) {
    temp = root->left;
} else {
    temp = root->right;
}

Which means he checks to see if root->left is "true":

 root->left ? ...

If it is defined in temp the value of before of ::

 temp = <condição passou> ? root->left : ....

If "false" sets the value afterward of : to the temp:

 temp = <condição não passou> ? .... : root->left

A simpler example:

#include <stdio.h>

int main(void) {
    int a = 10;

    printf( "O valor de 'a' é igual a 1? Resposta: %s\n", (a == 1) ? "sim" : "não" );

    printf( "O valor de 'a' é igual a 10? Resposta: %s\n", (a == 10) ? "sim" : "não" );

    return 0;
}

The result will be (test on ideone):

Is the value of 'a' 1? Answer: no

Is the value of 'a' equal to 10? Answer: yes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.