Search code examples
c++c++11if-statementassignment-operatorauto

An error related to assignment within an if-statement condition


What could be wrong with this construct?

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


          //do something
}

where diff is of type ptrdiff_t and objRef is of type std::vector.

The following compiler errors are generated for the above statement:

   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                                            ^

Solution

  • According to this answer: https://stackoverflow.com/a/7837092/159145 the contents of an if statement condition must be either an expression or a single-variable-declaration.

    In your case, auto idx = diff * 2 is a single-variable-declaration, but because you combined it with <= objRef.size() the if's condition then ceases to be a single-variable-declaration, but it isn't an expression either because it includes a declaration - hence the compiler complains.

    Change your code to compute idx before the if statement:

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

    If you want to restrict the scope of idx then use an anonymous-scope:

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

    ...or just elide the auto idx entirely, assuming you have no further use for it:

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