使用C语言编译堆栈程序时出现错误消息

时间:2015-09-24 03:59:17

标签: c++ c compiler-errors

我写了一个堆栈示例,但它在编译时显示错误消息。

在开关案例4中:exit();这一行是问题:想想

64  9   C:\Users\pavilion 15\OneDrive\Documents\stack.cpp   [Error] return-statement with a value, in function returning 'void' [-fpermissive]

这是我在编译此代码时看到的错误消息。有人可以帮我解决这个问题吗?

#include<stdio.h>
#include<conio.h>
#define MAX 5

int stack[MAX];
int top = -1;

void push(int);
int pop();
void display();

main(){

    int choice,num;
    while(1){
        printf("Enter your choice\n");
        printf("1.Push\n");
        printf("2.Pop\n");
        printf("3.Display\n");
        printf("Exit\n");
        scanf("%d", &choice);

        switch(choice){
            case 1:
                printf("Enter a number");
                scanf("%d", &num);
                push(num);
                break;
            case 2:
                 num = pop();
                 break;
            case 3:
                display();
                break;
            case 4:
                exit(1);
            default:
                printf("invalid input");
        }
    }

}


void push(int element){

    if(top == MAX-1 ){
        printf("Stack OverFlow");
        return;
    }
    top = top +1;
    stack[top]=element;
}

void pop(){
    int element;
    if(top == -1){
        printf("Stack is empty\n");
        return;
    }
    element = stack[top];
    top = top - 1;
    printf("%d has been deleted", element);
    return element;
}

void display(){
    int i;
    if(top==-1){
        printf("stack is empty!");
        return;
    }
    printf("\n\n");
    for(i=top;i>0;i--)
    printf("%d\n", stack[i]);
}

enter image description here

3 个答案:

答案 0 :(得分:2)

您宣布int pop(),但您定义了void pop(),并在定义中尝试return element

现在执行num = pop()时通常会导致错误,因为它无法找到您转发的函数的正确定义,但编译器因函数{{1没有很好的形成。

答案 1 :(得分:0)

您无法从void函数返回值。

void pop(){
    int element;
    if(top == -1){
        printf("Stack is empty\n");
        return;
    }
    element = stack[top];
    top = top - 1;
    printf("%d has been deleted", element);
    return element;
}

需要int pop()

答案 2 :(得分:0)

您无法从pop()返回元素 - 它是void(无返回类型)...

...正如错误消息所说的那样!

最简单的解决方法是让它返回int,但是您需要一个特殊的返回码来指示错误。 或者:int pop(int *v) - 失败时返回0或成功时返回1,并填充v