The Linux kernel source has a lot of array literals like this:
enum {
FOO,
BAR
};
static const char* const names[] = {
[FOO] = "foo", /* wtf is this? */
[BAR] = "bar",
};
Here each line explicitly indicates the index within the array of the supplied value instead of relying on ordering.
I don't know the phrase to search for - what is this called? What standard defines it? (Or is it a GNU extension?) Can I do this in C++ or just plain C? Experimenting with gcc
, I find with the above in test.c
,
$ gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
these commands return success:
$ gcc -Wall -c test.c
$ gcc -Wall -c --std=c90 test.c
$ gcc -Wall -c --std=gnu90 test.c
$ gcc -Wall -c --std=iso9899:1990 test.c
$ gcc -Wall -c --std=c1x test.c
and these commands fail with various complaints about lambdas and operator=
:
$ g++ -Wall -c test.c
$ g++ -Wall -c --std=c++98 test.c
$ g++ -Wall -c --std=gnu++98 test.c
$ g++ -Wall -c --std=c++0x test.c
$ g++ -Wall -c --std=gnu++0x test.c
That suggests this is valid C (in just about any dialect) but not C++. But I'm skeptical. I don't remember seeing this used anywhere but the Linux kernel. I also don't see it described in, for example, this list of constructs valid in C but not C++.