0

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?

5
  • Why do you need this i at all? Just do if (integer == 5 && function()) Commented Jan 25, 2022 at 22:30
  • if int integer = 5 then if ( integer == 5 ) will always be true... Commented Jan 25, 2022 at 22:33
  • @EugeneSh. Because function() does something fancy and I want the returned value. The code is simplified. Commented Jan 25, 2022 at 22:34
  • @EugeneSh. My first option makes i available outside the scope of the if statement. Not a big deal, but I liked that it wasn't. Commented Jan 25, 2022 at 22:39
  • @EugeneSh.if (int i = function()) {} std::cout << i; will give error: ‘i’ was not declared in this scope, so the if statement has a scope similar to for. Commented Jan 25, 2022 at 22:47

4 Answers 4

2

As an alternative to the other answers, since C++17 you can also declare a variable in the scope of the if in addition to the condition (rather than using a declaration directly in the condition):

if(int i; integer == 5 && (i = function()))

You might want to add an initializer to i for a default value.

Sign up to request clarification or add additional context in comments.

Comments

0
int i;
if (integer == 5 && (i = function())) {

This does what you want, and only calls function() if integer == 5. If it's not 5 it will short circuit and skip the right-hand side.

4 Comments

Unrelated: An extra set of braces around int i; and the if can be helpful in preventing i from leaking into other code.
@user4581301, without the extra set of braces it gives "error: lvalue required as left operand of assignment".
@Veda They meant braces { and } around the whole code block shown in the answer including the if body.
@user17732522, Thanks, missed that. Actually, that would work.
0

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.

Comments

0

I only want to call function() if the first check is true.

Then I would simply use two ifs:

int integer = 5;
if (integer == 5) {
  int i = function();
  if (i) {
    ...
  }
}

If you really want a single if statement, you could move the declaration of i outside of the statement, like you showed, and then wrap it in a local scope to restrict its use:

...
{
  int i;
  if (integer == 5 && (i = function())) {
    ...
  }
}
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.