c - 为什么不能全局定义结构成员?

标签 c struct

当您全局定义 struct 时,为什么不能也全局定义结构成员(除了使用初始化语法之外)?我从 clang 得到的错误是 system_1 有一个“未知类型名称”。

如果您在函数中定义结构,例如 main(),那么您不会遇到任何问题。

typedef struct Light_System {
    int redLightPin;
    int yellowLightPin;
    int blueLightPin;
} Light_System;

Light_System system_1;

# "Light_System system_1 = {4, 0, 0}" works

system_1.redLightPin = 4; # doesn't work

int main(int argc, char *argv[]) {
    # placing everything in here works
    # placing just "system_1.redLightPin = 4;" here makes it work.
    printf("%d\n", system_1.redLightPin);
    return 0;
}

我希望我能够在全局范围内定义结构的成员。

最佳答案

When you define a struct globally, why can't you define the structure members globally (outside of using the initializer syntax)?

因为您要做的不是定义初始化。这是一个任务。您可以在全局范围内声明、定义和初始化,但不能赋值。

这不仅适用于结构。它也适用于变量。在函数之外,您只能声明和初始化变量。你不能做常规作业,或者其他任何事情。我不能 100% 确定细节,但我相当有信心您无法在全局范围内做任何在编译期间无法完成的事情。

这样就可以了:

int x=5;

但不是这个:

int x;
x = 5;

好吧,实际上它是有效的,但会产生关于 warning: data definition has no type or storage classwarning: type defaults to 'int' in declaration of 'x' 的神秘警告 然而,仅仅因为它编译,它不会做你认为它会做的事。实际上,你不理解的神秘警告通常是一个很好的指标,表明代码会做一些你既不想也不理解的事情。这段代码所做的是 x隐式重新声明,然后是 初始化。如果之前没有初始化是允许的,所以这是无效的:

int x = 3;
x = 5; // Not ok, because x is already initialized

这里的错误信息清楚地说明了为什么前面的例子被编译:error: redefinition of ‘x’

同样,这也是无效的:

int x = foo();  

它给出了这个错误:

main.c:3:7: error: initializer element is not constant
 int x = foo();
         ^~~

关于c - 为什么不能全局定义结构成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617945/

相关文章:

C 中的计数排序 - 错误 : Use of undeclared identifier

c - scandir 真的是线程安全的吗?

c - 初始化结构

c++ - 一直运行到某个值链表

c - 子请求未发送或请求挂起

c - 了解 C 变量

c - 转义序列在 scanf() 函数中的实际行为

c - 将结构作为值参数传递给线程

python - 将 4 个整数打包为一个字节?

struct - 使用 to_owned() 是更新结构的惯用方法吗?