This is the part of a program for implementing queue with ring buffer in C.
And I don't understand the line 8-9.
What exactly does this line if(q->rear == q->max) q->rear = 0;
mean?
if the rear index equals the max capacity... then assign zero to rear? T_T Help me please!
int Enque(IntQueue* q,int x)
{
if (q->num >= q->max)
return -1;
else {
q->num++;
q->que[q->rear++] = x;
if(q->rear == q->max)
q->rear = 0;
return 0;
}
}
q->que[]
is an array of integers. Individual array q->que[]
integer elements are accessed by specifying their index in the array such as: q->que[n];
where n
is a value from 0
to (q->max - 1)
.
q->rear
represents an index into the array q->que[]
. The value of q->rear
may be anywhere from 0
through (q->max -1)
. Hence, if q->rear
ever becomes equal to q->max
, it would represent an index that is beyond the end of the q->que[]
array, and (being a circular queue) must be positioned back to the beginning of the array (q->que[0]
).
Hence, the logic of:
if (q->rear == q->max)
q->rear = 0;