Alex Koay Alex Koay - 1 year ago 80
C Question

What happens if I define a 0-size array in C/C++?

Just curious, what actually happens if I define a zero-length array

int array[0];
in code? GCC doesn't complain at all.

Sample Program

#include <stdio.h>

int main() {
int arr[0];
return 0;


I'm actually trying to figure out if zero-length arrays initialised this way, instead of being pointed at like the variable length in Darhazer's comments, are optimised out or not.

This is because I have to release some code out into the wild, so I'm trying to figure out if I have to handle cases where the
is defined as
, which happens in some code with a statically defined
int array[SIZE];

I was actually surprised that GCC does not complain, which led to my question. From the answers I've received, I believe the lack of a warning is largely due to supporting old code which has not been updated with the new [] syntax.

Because I was mainly wondering about the error, I am tagging Lundin's answer as correct (Nawaz's was first, but it wasn't as complete) -- the others were pointing out its actual use for tail-padded structures, while relevant, isn't exactly what I was looking for.

Answer Source

An array cannot have zero size.

ISO 9899:2011

If the expression is a constant expression, it shall have a value greater than zero.

The above text is true both for a plain array (paragraph 1). For a VLA (variable length array), the behavior is undefined if the expression's value is less than or equal to zero (paragraph 5). This is normative text in the C standard. A compiler is not allowed to implement it differently.

gcc -std=c99 -pedantic gives a warning for the non-VLA case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download