Confusion with commas in ternary expression

Viewed 1874

I found the following interesting code today:

SomeFunction(some_bool_variable ? 12.f, 50.f : 50.f, 12.f)

I created a small sample to reproduce the behavior:

class Vector3f
{
public:
    Vector3f(float val)
    {
        std::cout << "vector constructor: " << val << '\n';
    }
};

void SetSize(Vector3f v)
{
    std::cout << "SetSize single param\n";
}

void SetSize(float w, float h, float d=0)
{
    std::cout << "SetSize multi param: " << w << ", " << h << ", " << d << '\n';
}

int main()
{
    SetSize(true ? 12.f, 50.f : 50.f, 12.f);
    SetSize(false ? 12.f, 50.f : 50.f, 12.f);
}

(Live Sample)

The result I get from running the above code is:

clang++ -std=c++14 -O2 -Wall -pedantic -lboost_system -lboost_filesystem -pthread main.cpp && ./a.out
main.cpp:29:20: warning: expression result unused [-Wunused-value]
    SetSize(true ? 12.f, 50.f : 50.f, 12.f);
                   ^~~~
main.cpp:30:21: warning: expression result unused [-Wunused-value]
    SetSize(false ? 12.f, 50.f : 50.f, 12.f);
                    ^~~~
2 warnings generated.
SetSize multi param: 50, 12, 0
SetSize multi param: 50, 12, 0

What I was expecting in both cases was that a single parameter would be passed to SetSize(float). However, two parameters are passed which I find extremely confusing (especially since ternary has precedence over comma; so I assumed the comma was not delimiting function arguments in this case). For example, if using true, the ternary should result in 12.f, 50.f. In this expression, the value to the left of the comma gets dropped/ignored, so I'd expect the end result to be:

SetSize(50.f);

The second part of the confusion is that whether we use true or false in the ternary, the same 2 values are passed to the function. The true case should be h=12, w=50 I'd think...

I see the compiler is trying to warn me about something, but I can't quite understand what's going on. Can someone decompose this logic and explain the result in a step by step fashion?

3 Answers
Related