Spikatrix
Spikatrix

Reputation: 20252

What do I get if I declare an array without a size in global scope?

In one of the answers in Tips for golfing 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 that the above program exhibits UB (but who cares in code golf?). But the thing that I don't understand is the s[] in global scope. I know that when the type of a global variable isn't specified, it defaults to int. I created a small program which surprisingly compiles:

#include <stdio.h>

int s[];
int main(void)
{
    printf("Hello!");
}

though it emits one warning:

prog.c:23:5: warning: array 's' assumed to have one element [enabled by default]
 int s[];
     ^

Upvotes: 5

Views: 625

Answers (1)

edmz
edmz

Reputation: 8492

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

s is an incomplete type. That's why you cannot sizeof it. As @BLUEPIXY suggests, it's initialized with zero because it's declared in global scope making a "tentative definition".

int i[];
the array i still has incomplete type, the implicit initializer causes it to have one element, which is set to zero on program startup.

Now,

Will this be useful anywhere?

It's pretty useless if you're just using s[0] because at that point you go for s; directly. But, if you need an array with a certain size and you don't care about UBs, it's "okay".

Upvotes: 1

Related Questions