c - 为什么我可以用没有类型的“静态”限定符声明一个变量?(在 C 中)
问题描述
在学习static
qualifier 时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;
}
解决方案
没有显式类型名称声明的变量被假定为 type int
。该规则在 c99 标准中被撤销。
如果您的变量类型是 char 或 float,则这段代码将不起作用。
这与您可以使用unsigned
代替unsigned int
、short
代替short int
和static
代替的原因相同static int
。最好用 明确限定变量int
。
推荐阅读
- python - 使用索引和列标题将 Pandas 数据帧中的位置复制到另一个数据帧
- syndesis - 在 Linux 上安装 minishift 和 syndesis 的问题
- c - 在 C 中添加分数作为分子和分母
- pandas - Python将CSV文件转换为不同的输出
- azure - Azure - Microsoft azure 是否支持 SFTP
- javascript - 带有嵌套吸气剂的对象?
- spartacus-storefront - 如何在 /cms/pages OCC 端点中填充自定义 cms 组件的自定义属性
- python - FiPy 方程组发散。建议?
- java - RestControllerAdvice 处理 INTERNAL_SERVER_ERROR 时返回两个 JSON 对象
- sql-server - ASP.NET Core 中 SQL 的复选框