Why would you use the ternary operator without assigning a value for the “true” condition (x = x ?: 1)

前端 未结 7 1647
旧时难觅i
旧时难觅i 2020-12-03 09:38

In the Android open-source qemu code I ran across this line of code:

machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */

7条回答
  •  失恋的感觉
    2020-12-03 10:21

    I feel the other answers do not answer the question in the title and also taking the tag c into account. Therefore I add another answer.

    I use this syntax to prevent my code from getting ugly through if-statements.

    foo(1) == TRUE ?: error_quit("foo(1) failed");
    foo(2) == TRUE ?: error_quit("foo(2) failed");
    foo(3) == TRUE ?: error_quit("foo(3) failed");
    foo(4) == TRUE ?: error_quit("foo(4) failed");
    

    You can see the actual function call right in the beginning of the line. Compared it to the versions below, where the leading if obstructs the direct view of the function call.

    if (foo(1) == FALSE) error_quit("foo(1)" failed");
    if (foo(2) == FALSE) error_quit("foo(2)" failed");
    if (foo(3) == FALSE) error_quit("foo(3)" failed");    
    if (foo(4) == FALSE) error_quit("foo(4)" failed");
    

    or even harder to read:

    if (foo(1) == FALSE){
      error_quit("foo(1)" failed");
    }
    
    if (foo(2) == FALSE){
      error_quit("foo(2)" failed");
    }
    
    if (foo(3) == FALSE){
      error_quit("foo(3)" failed");
    }
    
    if (foo(4) == FALSE){
      error_quit("foo(4)" failed");
    }
    

提交回复
热议问题