Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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[];
     ^
  • What is s in the above program? Is it an int* or something else?
  • Will this be useful anywhere?
like image 241
Spikatrix Avatar asked Nov 09 '22 12:11

Spikatrix


1 Answers

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".

like image 74
edmz Avatar answered Nov 14 '22 22:11

edmz