1
void test()
{
    string s = " ,";
    if (boost::trim_if(s, boost::is_any_of(" ,")), s.empty())
    {
        cout << "empty";
    }
    else
    {
        cout << s << endl;
    }
}

According to this How does the Comma Operator work, the expression is supposed to equal to boost::trim_if() which returns void. But it can work now, so it executes boost::trim_if() and s.empty(). Can I rely on this kind of expression?

You maybe say I should write code like this:

boost::trim_if(s, boost::is_any_of(" ,"));
if (s.empty())
{
    cout << "empty";
}

But I'm in a condition that our old code is

string s;
if(FAILED(GetStringFromAPI(s)) || s.empty() )
{
}

I want to just modify one line

if(FAILED(GetStringFromAPI(s)) || (boost::trim_if(...), s.empty()) )
{
}
Tas
  • 7,023
  • 3
  • 36
  • 51
Administrator
  • 254
  • 1
  • 8
  • @FrançoisAndrieux, yes I know it checks s.empty(). I want to know if it would definitely execute the left part of the comma. – Administrator Dec 14 '18 at 03:29
  • 1
    It evaluates all it's operands, left to right. – François Andrieux Dec 14 '18 at 03:38
  • The question you linked to is about the relative precedences of assignment and the comma and does not say what you think it says. (It says that `x = a, b` means `(x = a), b`, not `x = (a,b)`.) – molbdnilo Dec 14 '18 at 07:00

1 Answers1

3

Yes this is completely fine to use. cppreference says this (empahsis mine):

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins

Note that like other operators, the comma operator can be overridden, in which case the above may not hold true.

Tas
  • 7,023
  • 3
  • 36
  • 51