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

前端 未结 7 1667
旧时难觅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:24

    This is a GCC extension that means "if the condition is true, use it, else use this other value", so

    machine->max_cpus = machine->max_cpus ?: 1;
    

    is shorthand for

    machine->max_cpus = machine->max_cpus ? machine->max_cpus : 1;
    

    although if the conditional has side-effects, it will only be run once

提交回复
热议问题