I have a snippet of code that defines (what I believe to be) an empty array, i.e. an array containing no elements:
int a[] = {};
I compiled the snippet with gcc with no problem
A colleague attempting to get that same code to compile under MSVS made the modification:
int* a = NULL;
No he obviously thought that was an equivalent statemnent that would be acceptable to the MSVS compiler.
However, later in the code I retrieve the no. of elements in the array using the following macro:
#define sizearray(a) (sizeof(a) / sizeof((a)[0]))
when doing so:
sizearray({}) returns 0
this is as I would expect for what I believe to be a definition of an empty array
sizearray(NULL) returns 1
I'm thinking that sizeof(NULL)/sizeof((NULL)[0]))
is actually 4/4 == 1
as NULL == (void*)0
My question is whether:
int a[] = {};
is a valid way of expressing an empty array, or whether its poor programming practice.
Also, is it the case that you can't use such an expression with the MSVS compiler, i.e. is this some sort of C99 compatibility issue?
UPDATE:
Just compiled this:
#include <stdio.h>
#define sizearray(a) (sizeof(a) / sizeof((a)[0]))
int main()
{
int a[] = {};
int b[] = {0};
int c[] = {0,1};
printf("sizearray a = %lu\n", sizearray(a));
printf("sizearray b = %lu\n", sizearray(b));
printf("sizearray c = %lu\n", sizearray(c));
return 0;
}
using this Makefile:
array: array.c
gcc -g -o array array.c
My compiler is:
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9)
compiles without any complaint, output looks like this:
bph@marvin:~/projects/scratch/c/array$ ./array
sizearray a = 0
sizearray b = 1
sizearray c = 2
very curious? could it secretly be a C++ compiler, not a C compiler?
Tried John Bodes suggestion of additional compiler flags and can confirm that the compilation does then fail:
gcc --std=c11 --pedantic -Wall -g -o array array.c
array.c: In function ‘main’:
array.c:7:15: warning: ISO C forbids empty initializer braces [-Wpedantic]
int a[] = {};
^
array.c:7:9: error: zero or negative size array ‘a’
int a[] = {};
^
Makefile:2: recipe for target 'array' failed
make: *** [array] Error 1