Reputation: 1774
bool EnQueue(Queue *pq, Item item) {
// 1. create a new node
Node *node;
if (QueueIsFull(pq))
return false;
else {
node = malloc(sizeof(Node));
if (node == NULL) {
fprintf(stderr, "Unable to allocate memory");
exit(EXIT_FAILURE);
}
}
// 2. Copy the item to the node, update next
node->item = item;
node->next = NULL;
// 3. update the rear of the queue (and front if first object)
pq->rear->next = node;
pq->rear = node;
pq->front = pq->front || NULL; // ***********************
// 4. update the queue size
pq->items++;
return true;
}
The starred line gives me the following warning:
q.c:49:15: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
pq->front = pq->front || NULL;
If I remove the ||
, and just set it to one or the other value, it works fine with no warning. Why does ||
give a warning?
Upvotes: 0
Views: 68
Reputation: 224437
The logical OR operator ||
results in either 0 if both arguments are 0 (or NULL) or 1 otherwise. So what that statement is doing is setting pq->front
to the integer value 0 or 1.
You say you want the result to be the first non-null value, similar to how or
works in Python. If that's the case, the statement would essentially do nothing, as it would just assign pq->front
back to itself if non-null or to NULL if it is NULL.
What you probably were looking for is:
if (!pq->front) pq->front = node;
Which would set the front of the queue to node
if the queue is empty.
On a related note, this is a problem:
pq->rear->next = node;
if pq->rear
is NULL. To fix both issues, change this:
pq->rear->next = node;
pq->rear = node;
pq->front = pq->front || NULL;
to this:
if (!pq->front) {
pq->front = node;
pq->rear = node;
} else {
pq->rear->next = node;
pq->rear = node;
}
This of course assumes that if either pq->front
or pq->rear
is NULL then the other is also NULL.
Upvotes: 1