Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition operator "?:" and LPCTSTR in function header

Tags:

c++

atl

mfc

Maybe anyone can explain this to me:

bool Func1(LPCTSTR sData)
{
    if (sData) { ... }
}

And I called the function like this:

CString str = _T("");
Func1((str.IsEmpty() ? NULL : str));

And 'sData' inside function is never NULL, it is allways empty string but not NULL, why? Eddited code like this:

LPCTSTR strNull = NULL;
Func1((str.IsEmpty() ? strNull : str));

In this case it works correct.

like image 937
Ramunas Avatar asked Sep 07 '16 14:09

Ramunas


1 Answers

This is caused by the need to convert both the second and third operands to a common type.
(The result can't have different types depending on whether the condition is true or not.)

The first parameter is equivalent to

str.IsEmpty() ? CString(NULL) : str

since NULL doesn't have a type that you convert a CString to.
And CString(NULL) constructs an empty CString.

The second is equivalent to

str.IsEmpty() ? strNull : (LPCTSTR) str

since CString is convertible to LPCTSTR but not the other way around.

Inlining the cast,

    str.IsEmpty() ? (LPCTSTR) NULL : str

should give the same effect as the second.

like image 96
molbdnilo Avatar answered Sep 23 '22 21:09

molbdnilo