What will I get if I declare an array without size in the global scope?

In one of the answers to Golf Tips in C , I saw this code (ungolfed version):

s[],t; main(c){ for(scanf("%*d "); ~(c=getchar()); s[t++]=c) putchar(s[t]); } 

I think the above program shows UB (but who cares about code golf?). But I do not understand that it is s[] on a global scale. I know that when the type of a global variable is not specified, it defaults to int . I created a small program that compiles unexpectedly:

 #include <stdio.h> int s[]; int main(void) { printf("Hello!"); } 

although it gives one warning:

 prog.c:23:5: warning: array 's' assumed to have one element [enabled by default] int s[]; ^ 
  • What is s in the above program? Is it int* or something else?
  • Would it be useful anywhere?
+5
source share
1 answer

What is s in the above program? Is it int * or something else?

s is an incomplete type. That is why you cannot sizeof it. As @BLUEPIXY suggests, it is initialized to zero because it is declared in the global scope, creating a "preliminary definition".

int i[];
the array I still have an incomplete type, the implicit initializer makes it have one element that is set to zero when the program starts.

Now

Would it be useful anywhere?

This is pretty useless if you just use s[0] , because at this point you start s; directly s; . But, if you need an array with a certain size, and you don't care what UB is, it's "good."

+1
source

All Articles