K.Robert K.Robert - 1 month ago 7
C++ Question

Call constructor in if condition as a part of the comma expression?

Here is my code.

#include<iostream>
#include<string>


struct Sales_data {
Sales_data() = default;

std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};

int main()
{
bool a = true;
if (Sales_data item, a)
std::cout << a << std::endl;
}


I don't know why the compiler tell me expression must have bool type (or be convertible to bool).

Answer

Because that's not a valid if-statement. It's not a valid statement of any kind, in any context. This is also invalid:

bool a;
Sales_data item, a;   // what does this mean?!

And this is invalid:

bool a;
bool b = Sales_data item, a;  // ???

In C++17 you can do what you want, but using different syntax:

if (Sales_data item; a)
  ...

This is analogous to the initializer in a for statement:

for (Sales_item item; expr; expr)
  ...

Statements must be separated by ; not commas.