I have this code:
#include <iostream>
int function() {
return 2;
}
int main( void )
{
int integer = 5;
if (integer == 5 && int i = function()) {
std::cout << "true\n";
} else {
std::cout << "false\n";
}
}
It’s giving an error:
test.cpp: In function ‘int main()’:
test.cpp:10:23: error: expected primary-expression before ‘int’
10 | if (integer == 5 && int i = function()) {
| ^~~
test.cpp:10:22: error: expected ‘)’ before ‘int’
10 | if (integer == 5 && int i = function()) {
| ~ ^~~~
| )
The order of the parts in the if statement is important to me; I only want to call function() if the first check is true. Options I found to fix the error:
int i;
if (integer == 5 && (i = function())) {
And this, but this does not have the wanted behavior (it always calls function):
if (int i = function() && integer == 5) {
Any other options? I’m also unsure what rule I am violating with my first piece of code. Why isn’t it ok?
>Solution :
If you want an expression that allows you to control the scope of i, and control whether the function gets called, I’d use the conditional operator, https://en.cppreference.com/w/cpp/language/operator_other, aka ternary operator
#include <iostream>
int function() {
return 2;
}
int main(void)
{
bool boolean_expression = true;
if (int i = boolean_expression ? function() : 0) {
std::cout << "true\n";
}
else {
std::cout << "false\n";
}
}
Or you can just add an additional scope either inside or outside the if statement. If these are heavy or RAII objects instead of simple integer and bool then I’d go with an additional if statement or helper function.