Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a LPCTSTR variable is null or empty

Tags:

c++

the below code is not working. Here I want to check whether lpClassName is null or empty.

static HRESULT WINAPI ExampleMethod(
    __in_opt  LPCTSTR lpClassName)
{
    //code to check whether lpClassName is null or empty
    if( lpClassName == 0)
        return 0;

    if(*lpClassName) == L'\0')
        return 0;           
}
like image 382
Mami Avatar asked Dec 21 '22 01:12

Mami


1 Answers

I use a shorter form:

if (lpClassName == NULL || lpClassName[0] == 0)

There's no need to get the whole length of the string if all you need is to test for empty. The short circuit rules will prevent the second half of the statement from causing an error if the pointer is null.

Beyond that I expect the code in your question would work as well.

Edit: In this case the pointer appears to be coming from CreateWindowEx, which means it might not be an actual string pointer but an ATOM value instead. The way to tell the difference is to check that the upper bits are all zero. Microsoft uses the same convention for resource IDs and provides the IS_INTRESOURCE macro to test for this condition.

like image 65
Mark Ransom Avatar answered Jan 07 '23 17:01

Mark Ransom