static struct astr {
int a;
};
static const struct astr newastr = {
.a = 9,
};
Run Code Online (Sandbox Code Playgroud)
我得到:警告:空声明中无用的存储类说明符
如果我把它改成
static struct astr {
int a;
} something;
Run Code Online (Sandbox Code Playgroud)
那么警告将被修复。
以下也没有给出该警告
struct astr {
int a;
};
static const struct astr newastr = {
.a = 9,
};
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下这是怎么回事吗?
当您有结构定义但未声明任何变量时,您会收到警告。例如,以下内容将给出警告:
static struct s {
int a;
};
Run Code Online (Sandbox Code Playgroud)
这相当于:
struct s {
int a;
};
Run Code Online (Sandbox Code Playgroud)
它定义了结构s但不声明任何变量。即,没有与之关联的存储,因此没有任何内容可以应用static。
但如果你这样做:
static struct s {
int a;
} x;
Run Code Online (Sandbox Code Playgroud)
然后就不会出现警告,因为x除了定义结构之外,您还声明了变量s,因此static适用于x.
同样,如果struct s先前已定义,则可以执行以下操作:
static struct s x;
Run Code Online (Sandbox Code Playgroud)
没有任何警告。当然,如果需要,您可以选择提供初始化程序。