与if语句条件中的赋值相关的错误

时间:2018-02-16 03:41:25

标签: c++ c++11 if-statement assignment-operator auto

这个构造可能有什么问题?

    if((auto idx = diff * 2) <= objRef.size()){


          //do something
}

其中diff的类型为ptrdiff_t,objRef的类型为std :: vector。

为以上语句生成以下编译器错误:

   1 In file included from main.cpp:1:
   2 ./bt.hpp:597:28: error: expected ')'
   3                   i
   4                   if((auto idx = diff * 2) <= objRef.size())
   5 f((auto idx = diff * 2) <= objRef.size())
   6                            ^
   7 ./bt.hpp:597:22: note: to match this '('
   8                   if((auto idx = diff * 2) <= objRef.size())
   9                      ^
  10 ./bt.hpp:597:44: error: expected expression
  11                   if((auto idx = diff * 2) <= objRef.size())
  12                                            ^

1 个答案:

答案 0 :(得分:0)

根据这个回答:https://stackoverflow.com/a/7837092/159145 if语句条件的内容必须是表达式单变量声明

在您的情况下,auto idx = diff * 2是单变量声明,但由于您将其与<= objRef.size() if的条件相结合,因此不再是单一 - 变量声明,但它不是表达式,因为它包含一个声明 - 因此编译器会抱怨。

idx声明之前将代码更改为计算if

auto idx = diff * 2;
if( idx <= objRef.size() ) {

}

如果您想限制idx的范围,请使用匿名范围:

{
    auto idx = diff * 2;
    if( idx <= objRef.size() ) {

    }
}

...或者只是完全忽略auto idx,假设您没有进一步使用它:

if( diff * 2 <= objRef.size() ) {

}