Search code examples
c++if-statementvariablessyntaxinitialization

How to define variable and compare value inside if statement?


I have a code snippet like this:

if ((std::vector<int>::iterator iter = std::find(v.begin(), v.end(), i)) != v.end()) 
{
    // ....
}

But the compiler complains on this statement. However, changing my code into

std::vector<int>::iterator iter;
if ((iter = std::find(v.begin(), v.end(), i)) != v.end()) 
{
    // ....
}

Fixes the issue.

So, I was wondering why the first version does not work, and what is the return value of the statement below?

std::vector<int>::iterator iter = std::find(v.begin(), v.end(), i)

Solution

  • How to define variable and compare value inside if statement?

    Since you can do this by the language feature, if with init-statement, as below:

    if(auto iter = std::find(v.begin(), v.end(), i); // declare + initialize
      iter != v.end())                               // use in condition
    {
        // ....
    }
    

    You can declare, initialize, and use the variable to check in if statement by this syntax. By doing so, you will be able to restrict the scope of the such variable only in if-statement.


    I was wondering why the first version does not work[...]

    Because it is not valid C++ statement. You can not declare, initialize and use the variable as you shown in the first version.

    However, variable initialization and direct use to check is allowed as per the C++ language. Hence the second one worked!


    Side Note: You can simply use auto keyword to mention the verbose types usch as std::vector<int>::iterator.