首页 > 解决方案 > 为什么我可以用没有类型的“静态”限定符声明一个变量?(在 C 中)

问题描述

在学习staticqualifier 时C,我错误地编写了以下代码。我认为该getEven()函数不会被编译,但它运行良好。为什么我可以声明一个没有类型的变量?

我尝试了一些测试,发现没有类型的static变量的类型是4字节整数。

//This code works well.
int getEven(int i) {
static int counter = 0;
if (i%2==0) {
    counter++;
}
    return counter;
}

//I thought this code would make compile error, but it also works well.
int getEven_(int i) {
static counter = 0; //No type!
if (i % 2 == 0) {
    counter++;
}
    return counter;
}

标签: c

解决方案


没有显式类型名称声明的变量被假定为 type int。该规则在 c99 标准中被撤销。

如果您的变量类型是 char 或 float,则这段代码将不起作用。

这与您可以使用unsigned代替unsigned intshort代替short intstatic代替的原因相同static int。最好用 明确限定变量int


推荐阅读