Doubt with the ternary operator [duplicate]

1

What does the following expression mean:

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

I am in doubt if he is checking for the root->left pointer or comparing *temp with root->left , in which case, would not it have to be "=="?

    
asked by anonymous 12.12.2017 / 22:10

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;
}

In other words, it checks if root->left is "true":

 root->left ? ...

If is set to temp , the value of before of : :

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

If it is false, it will set the value after from : to 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 in ideone ):

  

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

     

Is 'a' equal to 10? Answer: yes

    
12.12.2017 / 22:28