Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define variable and compare value inside if statement? [duplicate]

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)
like image 540
heturing Avatar asked Oct 19 '25 18:10

heturing


2 Answers

How to define variable and compare value inside if statement?

Since c++17 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.

like image 122
JeJo Avatar answered Oct 21 '25 07:10

JeJo


With

if ((int a = 1) == 2) ...

you attempt to define and initialize a variable within an expression. That is not allowed.

But when you write

int a;
if ((a = 1) == 2) ...

you do a simple assignment in a nested expression. That is perfectly valid.

like image 35
j6t Avatar answered Oct 21 '25 09:10

j6t