首页 > 解决方案 > 错误:初始化元素不是 c 语言中的编译时常量

问题描述

最近我一直在做一个项目,该项目询问用户的姓名、年龄,并通过返回的响应确认或拒绝上述信息。我被代码中的这个错误消息难住了,我所做的每一次修改都只会带来更多的错误,而且我不确定我到底做错了什么。代码如下:

#include "cs50.h"
#include <stdio.h>

int main(void);
{
  //ask the user for their name
  string name = GetString();
  //prompts the user for their name
  scanf("What is your name?:%s\n", name);
  printf("Hello\n");
  }
  
 int age = GetInt();
{
   //ask user for their age
   scanf("How old are you:%i\n", age);
   printf("You are:\n");
 }
 
 //Ask user to confirm
 char confirm = GetChar();
 {
   if(confirm == 'Y' || 'y');
   printf("Thank you!");
  }
  else if(confirm == 'N' || 'n');
 {
  printf("Denied");
  }
 }

编译此代码会返回以下错误:

    project.c:13:12: error: initializer element is not a compile-time constant
 int age = GetInt();
           ^~~~~~~~
project.c:14:1: error: expected identifier or '('
{
^
project.c:21:17: error: initializer element is not a compile-time constant
 char confirm = GetChar();
                ^~~~~~~~~
project.c:22:2: error: expected identifier or '('
 {
 ^
project.c:26:3: error: expected identifier or '('
  else if(confirm == 'N' || 'n');
  ^
project.c:27:2: error: expected identifier or '('
 {
 ^
project.c:30:2: error: extraneous closing brace ('}')
 }
 ^
7 errors generated.

我尝试删除%iand %s,但这只会产生更多错误,我尝试删除;afterint main (void);并产生更多错误。我不是我做错了产生这些错误,任何帮助将不胜感激。谢谢你和欢呼!

标签: clinuxcs50

解决方案


您的语句不在函数内部,因此在编译时处理它以填充二进制文件的“全局”部分。因此,编译器必须能够静态计算 的初始值age

由于您正在调用一个函数,因此这是不可能的,因此您会得到错误。


推荐阅读