I'm working on a C program that implements a queue, and I'm encountering an issue with an infinite loop.
The program is supposed to perform insertion, traversal, and deletion operations on the queue.
However, I'm observing that the program enters into an infinite loop under certain conditions.
#include <stdio.h>
#define N 10
int queue[N];
int front = -1;
int rear = -1;
void insert();
void traverse();
void delete();
int main() {
insert();
traverse();
delete();
return 0;
}
void insert() {
int item;
if ((rear + 1) % N == front) {
printf("overflow");
} else if (front == -1 && rear == -1) {
scanf("%d", &item);
rear, front = 0;
queue[rear] = item;
} else {
scanf("%d", &item);
rear = (rear + 1) % N;
queue[rear] = item;
}
}
void delete() {
int item;
if (rear == -1 && front == -1) {
printf("underflow");
} else if (rear == front) {
rear, front = -1;
} else {
item = queue[front];
front = (front + 1) % N;
}
}
void traverse() {
int i = front;
if (front == -1 && rear == -1) {
printf("underflow");
} else {
while (i != rear) {
printf("%d", queue[i]);
i = (i + 1) % N;
}
printf("%d", queue[i]);
}
}
I am trying to input a number in the queue but instead of displaying that number, it is getting into an infinite loop.
I am using VS Code.
The infinite loop is because
rearis permanently set to -1 only. The issue is with this line of C code in yourinsert()function, which is supposed to set bothrearandfrontto 0 when an element is inserted into the empty queue:The above statement may not work as you think it does. Only
frontwill be set to 0. I have usedgcccompiler on Linux and it will not assign 0 torearwith such a statement. I am not sure what your VS Code compiler does with such a statement. You can try toprintfthe value ofrearduring an insertion of an element during the empty queue condition in VS Code and see ifreargets changed at all while executing the code.Change the code in your
insert()function to:The above should remove the infinite loop you are seeing.
For more clarity, you may like to check a previous Q&A on this same issue: How can I declare and define multiple variables in one line using C++?