sab669
sab669

Reputation: 4104

How are pointers evaluated in a C++ boolean expression?

I'm converting an old Borland C++ application to C# .NET

There's this class that looks like it's basically just a Doubly Linked List.

One of the methods looks like this:

MessagePtr CheckMessageList::First(MessageSourceTable _source)
{
  MessagePtr
    message = First();
  bool
    done = false;

  while (message && !done)
  {
    done = (bool) (message->SourceTable() == _source);
    if (!done)
      message = Next();
  }

  return (message);
}

I don't understand how while (message) is evaluated though.

In C# I have this:

public CheckMessage Fist(enums.MessageSourceTable table)
{
    CheckMessage message = First();
    bool done = false;

    while (message && !done)
    {
        done = message.SourceTable.Equals(table);

        if (!done)
            message = Next();
    }

    return message;
}

Which is invalid since it doesn't know how to handle that while statement.

I have virtually no experience with C++. Can anyone point me in the right direction?

edit; would this be the same thing, basically?

public CheckMessage Fist(enums.NYMSMessageSourceTable table)
{
    foreach (CheckMessage cm in _list)
    {
        if (cm.SourceTable.Equals(table))
            return cm;
    }

    return Last();
}

Upvotes: 2

Views: 1251

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 118001

In C++ pointers have implicit conversions to bool, where a pointer is "falsy" if it is equal to nullptr and "truthy" otherwise. So

while(message)

is equivalent to

while(message != nullptr)

Upvotes: 4

Related Questions