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;
}
Achal
  • 11,821
  • 2
  • 15
  • 37
Unknownpgr
  • 87
  • 10
  • 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: https://stackoverflow.com/a/8220672/159145 – Dai Aug 01 '19 at 03:41
  • @Dai I didn't know that. thanks :) – Unknownpgr Aug 01 '19 at 03: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. – Jonathan Leffler Aug 01 '19 at 03:54
  • @Dai / Jonathan Aptly put. why can't make comments as answer. It clears air for many. – Achal Aug 01 '19 at 04:07
  • Or the other way around: Why not writing an answer upfront? ;-) – the busybee Aug 01 '19 at 06:13

1 Answers1

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.

Abdul Alim Shakir
  • 1,128
  • 13
  • 26