Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Boolean check before variable declaration in if statement

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading