4

While studying static qualifier in C, I wrote the following code by mistake. I thought that getEven() function would not be compiled but it works well. 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.

//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;
}
5
  • 7
    Earlier versions of the C language specification state that declarations without a type are int by default. Modern versions of C disallow this and always require an explicit type. See here: stackoverflow.com/a/8220672/159145
    – Dai
    Aug 1, 2019 at 3:41
  • @Dai I didn't know that. thanks :)
    – Unknownpgr
    Aug 1, 2019 at 3:49
  • 3
    "Earlier versions" means C90 standard and earlier (pre-standard) versions. The license to omit the type (default int) was removed from C99, but many compilers continued to allow it for reasons of backwards compatibility — in the case of GCC until version 5 when the default mode was switched from C90 to C11 (skipping C99). You can still turn off the warning by explicitly requesting C90 mode. Aug 1, 2019 at 3:54
  • @Dai / Jonathan Aptly put. why can't make comments as answer. It clears air for many.
    – Achal
    Aug 1, 2019 at 4:07
  • Or the other way around: Why not writing an answer upfront? ;-) Aug 1, 2019 at 6:13

1 Answer 1

5

A variable declared without an explicit type name is assumed to be of type int. This rule was revoked in the c99 Standard.

The piece of code will not work if your variable type is char or 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. It is better to explicitly qualify variables with int.

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.