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?
iat all? Just doif (integer == 5 && function())int integer = 5thenif ( integer == 5 )will always be true...if (int i = function()) {} std::cout << i;will giveerror: ‘i’ was not declared in this scope, so the if statement has a scope similar to for.