c - 错误:初始化元素不是 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.
我尝试删除%i
and %s
,但这只会产生更多错误,我尝试删除;
afterint main (void);
并产生更多错误。我不是我做错了产生这些错误,任何帮助将不胜感激。谢谢你和欢呼!
解决方案
您的语句不在函数内部,因此在编译时处理它以填充二进制文件的“全局”部分。因此,编译器必须能够静态计算 的初始值age
。
由于您正在调用一个函数,因此这是不可能的,因此您会得到错误。
推荐阅读
- html - 我想从模态正文和页脚中删除水平线?
- javascript - 如何在javascript上无休止地重复随机img?
- typo3 - 从 TYPO3 4 升级到 TYPO3 4.5 时出错
- javascript - 在 OnMouseOver 事件中设置状态返回 TypeError:无法读取属性 - React
- java - 如果类中没有这样的字段,如何在 id 上接收可嵌入对象?
- c - 将 sqlite 连接到 C 程序
- python - QPlainTextEdit 文本并在窗口的新行中增加文件名
- hive - 如何在 apache hive 中插入日期、布尔值?
- python - 我怎样才能以不同的方式编写它,以便不总是调用夹具?
- svn - Trac 可以从其他服务器连接到 SVN 存储库吗?