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)
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With