You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言报错:expected identifier or '(' before '}' token 问题求助

错误原因与解决方法:error: expected identifier or '(' before '}' token

错误根源

你的代码里有两处语法问题直接触发了这个编译错误:

  • while(1);末尾多了一个分号;:这个分号会让while循环变成空循环体,只会无限执行空操作,后面的菜单打印、输入选择、switch逻辑都脱离了循环,成为main函数的顶级代码。
  • 多余的闭合大括号}:在switch语句结束后,你额外加了一个},这个大括号没有对应的起始{,编译器无法识别它的作用,因此抛出错误。

修复步骤

  1. 移除while(1);末尾的分号,让后续代码成为while循环的循环体;
  2. 删掉switch结束后多余的那个},或者更规范地给while循环加上一对大括号,把所有循环内的代码包裹进去(推荐后者,代码可读性更强)。

修正后的完整代码

#include <stdio.h>
#include <stdlib.h>
struct stack
{
    int no;
    struct stack *next;
};
struct stack *p,*temp,*head;
void main()
{
    void push();
    void pop();
    void display();
    int choice;
    while(1) // 移除末尾分号
    { // 给while循环添加起始大括号
        printf("\n 1 Push");
        printf("\n 2 Pop");
        printf("\n 3 Display");
        printf("\n 4 Quit");
        printf("\n Enter your option: ");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            push();
            break;
        
        case 2:
            pop();
            break;

        case 3:
            display();
            break;

        default:
            exit(0);
        }
    } // 该大括号对应while的起始大括号
}
void push()
{
    temp=(struct stack*) malloc(sizeof(struct stack));
    printf("\n Enter no: ");
    scanf("%d", &temp->no);
    if (head==NULL)
    {
        head=temp;
        temp->next=NULL;
    }
    else
    {
        temp->next=head;
        head=temp;
    }
    printf("\n Element %d is pushed in to the stack", temp->no);
}
void pop()
{
    p=head;
    if(head==NULL)
    {
        printf("Stack is empty");
    }
    else
    {
        head=head->next;
        printf("Element %d is popped from the stack", p->no);
        free(p);
    }
}
void display()
{
    if(head==NULL)
    {
        printf("\n stack is empty");
    }
    else
    {
        p=head;
        printf("\n the elements present in the stack:\n");
        while(p!=NULL)
        {
            printf("%d ", p->no); // 增加空格优化输出格式
            p=p->next;
        }
    }
}

内容的提问来源于stack exchange,提问作者boredAhhDude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 20:15:26