I thought I knew VS 2008 C++ compiler really well:
CString str;
str.Empty();
LPCTSTR pStr = str.IsEmpty() ? NULL : str;
::MessageBox(NULL, pStr ? L"pStr is NOT null" : L"pStr is null", L"Result", MB_OK);
Can someone explain why am I getting this?
LPCTSTR pStr = str.IsEmpty() ? (LPCTSTR)NULL : str;
does return a NULL
.
It looks like this happens because the two expressions are not of the same type; MSDN Docs says
If both expressions are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type
A quote from a MSDN forum post:
5.16-3- in the standard describes the type coercion taking place here; the expression (B ? E1 : E2) can only have a single type, so if the types of expressions E1 and E2 are different, they must be coerced into a common, safe type before evaluation of either expression occurrs ... So, the type of E1 in this example is CString, and the type of E2 is int. The process described in 5.16-3- eventually concludes that the only safe type for both of these to convert to is CString.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With