Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange result from a C++/MFC compiler in VS 2008

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?

enter image description here

like image 591
c00000fd Avatar asked Sep 06 '25 21:09

c00000fd


1 Answers

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.

like image 58
Edward Clements Avatar answered Sep 08 '25 22:09

Edward Clements