C 中第一个参数为空的选择性参数?表达式 "var1 ?: var2"
Selective argument with first argument empty in C? expression "var1 ?: var2"
有时候不知道叫什么,用关键字也找不到。
这是另一个这样的例子。我刚刚在 C 程序中看到了这个表达式。 (qemu)
virt_flash_fdt(vms, sysmem, secure_sysmem ?: sysmem);
被调用函数的定义是这样的
static void virt_flash_fdt(VirtMachineState *vms,
MemoryRegion *sysmem,
MemoryRegion *secure_sysmem)
函数调用中的?:
运算符是什么?是“如果 secure_sysmem 不为空,则使用它,否则使用 sysmem”?这种语法叫什么? (具有默认值的选择性参数?)
这是对三元运算符的 GNU 扩展;相当于
virt_flash_fdt(vms, sysmem, secure_sysmem ? secure_sysmem : sysmem);
(除非secure_sysmem是一个有副作用的宏)
参见:https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html
来自该站点:
In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.
因此,在上面的调用中,如果第三个参数为非 NULL,则第三个参数将为 secure_sysmem
,否则为 sysmem
.
有时候不知道叫什么,用关键字也找不到。
这是另一个这样的例子。我刚刚在 C 程序中看到了这个表达式。 (qemu)
virt_flash_fdt(vms, sysmem, secure_sysmem ?: sysmem);
被调用函数的定义是这样的
static void virt_flash_fdt(VirtMachineState *vms,
MemoryRegion *sysmem,
MemoryRegion *secure_sysmem)
函数调用中的?:
运算符是什么?是“如果 secure_sysmem 不为空,则使用它,否则使用 sysmem”?这种语法叫什么? (具有默认值的选择性参数?)
这是对三元运算符的 GNU 扩展;相当于
virt_flash_fdt(vms, sysmem, secure_sysmem ? secure_sysmem : sysmem);
(除非secure_sysmem是一个有副作用的宏)
参见:https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html
来自该站点:
In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.
因此,在上面的调用中,如果第三个参数为非 NULL,则第三个参数将为 secure_sysmem
,否则为 sysmem
.