[英]Why can I declare a variable with 'static' qualifier without type? (in C)
While studying static
qualifier in C
, I wrote the following code by mistake. 在
C
研究static
限定符时,我错误地编写了以下代码。 I thought that getEven()
function would not be compiled but it works well. 我认为
getEven()
函数不会被编译但是效果很好。 why can i declare a variable without type? 为什么我可以声明一个没有类型的变量?
I tried some test and found that the type of static
variable without type is 4
byte integer. 我尝试了一些测试,发现没有类型的
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;
}
A variable declared without an explicit type name is assumed to be of type int
. 声明没有显式类型名称的变量的类型为
int
。 This rule was revoked in the c99 Standard. 该规则在c99标准中被撤销。
The piece of code will not work if your variable type is char or float. 如果您的变量类型是char或float,则该段代码将不起作用。
This is the same reason that you can use unsigned
instead of unsigned int
, short
instead of short int
, and static
instead of static int
. 这与使用
unsigned
而不是unsigned int
, short
而不是short int
和static
而不是static int
。 It is better to explicitly qualify variables with int
. 最好用
int
显式限定变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.