Brandon
Brandon

Reputation: 21

Why use a Pointer and its dereference in if statement in c++

I was looking for some c++ code, and was confused by if(ptr && *ptr), what does it do in this case?

// Process the data here.  We just break the data into separate pieces and 
// display it for the sake of simplicity.
char * a_pszBreak = NULL;
char * a_pszDataItem = (char*)s_aucDataBuffer;
do
{
    // The poll data is terminated by either a Carriage Return alone, or a
    // Carriage Return/Line Feed pair.
    a_pszBreak = strpbrk(a_pszDataItem, "\n\r");
    if (a_pszBreak && *a_pszBreak)
    {
        *a_pszBreak = 0;
        a_pszBreak++;
        LogPollData((const char *)a_pszDataItem);
    }
    a_pszDataItem = a_pszBreak;
} while (a_pszBreak && *a_pszBreak);

Upvotes: 1

Views: 1873

Answers (3)

sameerkn
sameerkn

Reputation: 2259

In if (a_pszBreak && *a_pszBreak) a_pszBreak is used to check whether a_pszBreak points to valid memory area i.e a_pszBreak is not NULL and *a_pszBreak is used to check whether memory pointed by a_pszBreak does not start with NULL character i.e \0.

In short if (a_pszBreak && *a_pszBreak) is used to check whether a_pszBreak points to a string of length atleast 1.

Upvotes: 0

nvoigt
nvoigt

Reputation: 77304

if (a_pszBreak && *a_pszBreak)

In C++, anything that can be interpreted as 0 is false and anything else is considered true for the purpose of statements.

So this ensures that the pointer is not NULL and that the contents of the first element the pointer points to is not null or 0 either.

Due to short circuiting, if the pointer is NULL, the second part will not be checked.

So in plain english, this if-statement checks if the pointer is not a nullptr and if the pointer does not point to an empty string.

Upvotes: 0

Jack
Jack

Reputation: 133577

it means that the pointer should point to something and in addition that something must be different from 0.

It's like (a_pszBreak != nullptr && a_pszBrealk[0] != '\0')

Upvotes: 6

Related Questions