4

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)
JeJo
  • 30,635
  • 6
  • 49
  • 88
heturing
  • 123
  • 1
  • 7
  • 1
    I assume this is pre-C++17 code? – Nicol Bolas Aug 28 '21 at 19:08
  • *"the compiler complaints on this statement"* -- what is the specific complaint? Is it [expected primary-expression before ‘…’](https://stackoverflow.com/questions/67756436/expected-primary-expression-before-c-compile-error)? – JaMiT Aug 28 '21 at 19:22
  • @JaMiT The first is **expected a ')'** at iter, and the second is **expected an expression** at !=. – heturing Aug 28 '21 at 19:38
  • @heturing I see. You're using clang, while that other question is based on gcc. Same issue, different compiler messages. (See my answer over there if you're still confused about what is going on here.) – JaMiT Aug 28 '21 at 20:47
  • Better duplicate: [c++ - Can I write this if statement with a variable declaration on one line? - Stack Overflow](https://stackoverflow.com/questions/45999057/can-i-write-this-if-statement-with-a-variable-declaration-on-one-line) – user202729 Dec 13 '21 at 10:51

2 Answers2

9

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88
2

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.

j6t
  • 9,150
  • 1
  • 15
  • 35