简体   繁体   English

为什么我可以使用'static'限定符声明一个没有类型的变量? (在C中)

[英]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 intshort而不是short intstatic而不是static int It is better to explicitly qualify variables with int . 最好用int显式限定变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在 C 中声明变量或函数是静态的? - Why declare a variable or function static in C? 如何在不使用C的情况下使用变量但不使用malloc()声明数组? - How can I declare an array with a variable, but without using malloc() in C? 为什么我们不能在 C 编程语言的结构中声明静态变量? - Why can't we declare a static variable within a structure in the C programming language? 如何检查变量是否为 C 中的“const”限定符类型? - How to check if a variable is of "const" qualifier type in C? 为什么在main中声明一个静态变量? - Why declare a static variable in main? “C”为什么我将变量声明为“指针”? - 'C' why I declare the variable as 'pointer'? 我们可以在 C 的不同函数中声明相同的局部静态变量吗? - can we declare the same local static variable in different functions in C? 为什么我必须先声明一个不相关的 struct file_handle 变量才能使用该类型? - why do I have to declare an irrelevant struct file_handle variable before I can use that type? 在C中不使用对象进行管理 - 为什么我可以在C中的函数中的任何位置声明变量? - Managing without Objects in C - And, why can I declare variables anywhere in a function in C? 我如何声明一个 int 类型的输入变量,例如。 输入 x(0 - How can i declare a int type input variable eg. take a input x(0<x<1000) in c?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM