0

I am working on code which uses a custom linked list class. The list class has the function:

void linkedList::expire(Interval *interval, int64 currentDt)
{
    node *t = head, *d;
    while ( t != NULL )
    {
        if ( t->addedDt < currentDt - ( interval->time + (((long long int)interval->month)*30*24*3600*1000000) ) )
        {
            // this node is older than the expiration and must be deleted
            d = t;
            t = t->next;

            if ( head == d )
                 head = t;

            if ( current == d )
                 current = t;

            if ( tail == d )
                 tail = NULL;

             nodes--;
             //printf("Expired %d: %s\n", d->key, d->value);
             delete d;
         }
         else
         {
            t = t->next;
         }
     }
}

What I don't understand is the first line of code in the function:

node *t = head, *d;

How is it that this code compiles? How can you assign two values to a single variable, or is this some shorthand shortcut? head is a member variable of type *node, but d isn't found anywhere else.

Danzo
  • 553
  • 3
  • 13
  • 26

2 Answers2

4

These are two definitions, not the comma operator1. They are equivalent to

node* t = head;
node* d;

1 the comma operator has the lowest precedence of all operators in C++, so invoking it requires parantheses:

node* t = (head, *d);

This would work properly if d was of type node**.

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
0

Generally in c++ you can list multiple definitions separating them with a comma:

int a,b,c,d;

will define 4 integers. The danger is that pointers are not handled in a way that might be obvious:

int* a,b,c,d;

Will declare a to be a pointer to an int, and the remaining will just be ints. Hence the not-uncommon practice of declaring pointers in the style:

int *a, *b; 

which declares two integer pointers.

Chris Becke
  • 750
  • 4
  • 10