rui314 / chibicc

A small C compiler
MIT License
9.69k stars 883 forks source link

VLA argument does not compile #40

Open tstanisl opened 3 years ago

tstanisl commented 3 years ago

This code does not compile:

int fun(int n, int a[n]);

Cmd: chibicc x.c -c Error:

x.c:1: int fun(int n, int a[n]);
                            ^ undefined variable

This is compliant C99 code using VLA.

ghost commented 3 years ago

I wanted to note that even though this uses VLA syntax, it does not actually declare a VLA! The declared argument a becomes a pointer to int implicitly by virtue of being an parameter declared as an array.

If you had instead written int (*a)[n], then it would (perhaps more expectedly) become a pointer to a VLA of int. (Though even then it does not compile in chibicc with a similar error.)

Note that the problem here is not using the VLA syntax in a parameter, it’s only that parameters declared before it are not visible in the parameter’s scope.

I tried using a global instead, and for char (*a)[x], chibicc failed compilation silently without output. For the char a[x] case (where there is no actual VLA), it worked fine for me.

// works fine (no VLA)
int x = 10;
void fun(char a[x]) { }
// fails silently (pointer to VLA)
int x = 10;
void fun(char (*a)[x]) { sizeof *a; }

However, if I don’t use sizeof nor try to subscript it or dereference it, it appears to work too. But then there is not much point in the parameter being there at all!

// works (unused pointer to VLA)
int x = 10;
void fun(char (*a)[x]) { }