I have a question about my code. This is my answer to programming project 1 in Chapter 10 of KNK's C Programming a Modern Approach (2nd Ed.).
The question is asking us to write a stack to see if a series of parentheses and/or braces are properly nested. The question explicitly asks the student to modify the code in 10.2 - an earlier part of the chapter. My compiler is giving me the error warning control may not reach end of non-void function
. The compiler is referring to the calling of the char pop(void)
function.
My only issue is this I don't see what is wrong with
char pop(void)
{
if (is_empty())
stack_underflow();
else
return contents[--top];
}
For if the stack pointer returns to zero then the program terminates and if not then a character is returned, namely contents[--top]
. Not only that - this is exactly how the example in section 10.2 instructs the student to write the pop
function. So it would seem to suggest KNK got it wrong unless it's an issue with a new version of C (the book uses C99). Clearly I'm missing something.
As a result I'm not even sure if my current code is correct as I cannot even run it in the first place.
Ideas for where I'm going wrong would be appreciated.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define STACK_SIZE 100
/* function declarations */
bool is_empty(void);
bool is_full(void);
void push(char);
char pop(void);
void stack_overflow();
void stack_underflow();
/* external variables */
char contents[STACK_SIZE] = {0};
int top = 0;
int main(void)
{
char ch;
printf("Enter parentheses and/or braces: ");
scanf("%c", &ch);
while(ch != '\n')
{
if(ch == '{' || ch == '(') push(ch);
else if(ch == '}' && pop() != '{')
{
printf("Parentheses/braces are not nested properly\n");
return 0;
}
else if(ch == ')' && pop() != '(')
{
printf("Parentheses/braces are not nested properly\n");
return 0;
}
scanf("%c", &ch);
}
if(is_empty())
printf("Parentheses/braces are nested properly\n");
else
printf("Parentheses/braces are not nested properly\n");
return 0;
}
bool is_empty(void)
{
return top == 0;
}
bool is_full(void)
{
return top == STACK_SIZE;
}
void push(char ch)
{
if (is_full())
stack_overflow();
else
contents[top++] = ch;
}
char pop(void)
{
if (is_empty())
stack_underflow();
else
return contents[--top];
}
void stack_overflow(void)
{
printf("Stack overflow\n");
exit(0);
}
void stack_underflow(void)
{
printf("Parentheses/braces are not nested properly\n");
exit(0);
}