<分区>
我想创建一个 if
,其中声明、分配和检查变量。如果变量的值是可接受的,我想在 if
主体中使用它。以下是我认为我可以如何做到这一点的示例:
if ((int result = Foo()) != 0) {
// use result
}
我假设 Foo()
返回一些值,该值被分配给 result
,并由赋值运算符 =
返回,最后检查针对 != 0
中的 0
。不幸的是,它会导致编译错误:
main.cpp:31:10: error: expected primary-expression before ‘int’
if ((int i = Foo()) != 0)
^
main.cpp:31:10: error: expected ‘)’ before ‘int’
为什么会出现这个错误?有什么方法可以修复它?