Is the following code C99 code or does it happen to be an extension of my compiler? (gcc)
Code:void func(void)
{
int a[10] = { [4] = 1, [7] = 1 };
}
this is the same as:
void func(void)
{
int a[10] = { 0, 0, 0, 0, 1, 0, 0, 1 };
}
Printable View
Is the following code C99 code or does it happen to be an extension of my compiler? (gcc)
Code:void func(void)
{
int a[10] = { [4] = 1, [7] = 1 };
}
this is the same as:
void func(void)
{
int a[10] = { 0, 0, 0, 0, 1, 0, 0, 1 };
}
C99 Standard: yesQuote:
Originally Posted by Laserve
C89 Standard: no
Regards,
Dave
Yes,
This is example is from C99 standard
EXAMPLE 9 Arrays can be initialized to correspond to
the elements of an enumeration by using designators:
Code:enum { member_one, member_two };
const char *nm[] = {
[member_two] = "member two",
[member_one] = "member one",
};
well well well well. the [4]=1 here refers to a[4]=1Code:int a[10] = { [4] = 1, [7] = 1 };
and [7]=1 refers to a[7]=1.so they are one. but i couldnt understand how the remaining elements, a[0], a[1].....took zero as the default value.lemme check it out
C defaults to a value of 0 when you "attempt" to initialise it so to speak. Can't really explain it well but this code explains it a bit better:
Notice how array "c" gets garbage values since we didn't initialise it at all, array "b" gets initialised to default 0 since we didn't specify what values we wanted. Array "a" also gets initialised to 0 unless specified, this causes the 5th and 8th cell of the array to hold a 1 due to our explicit initialisation.Code:#include <stdio.h>
int main(int argc, char **argv)
{
int a[10] = { [4] = 1, [7] = 1 };
int b[10] = { };
int c[10];
int i;
for (i = 0; i < 10; i++)
{
printf("%d %d %d\n",a[i],b[i],c[i]);
}
return 0;
}
I learn something new every day!
To explain it in simple terms, all uninitialized array memebers are set to zero. The only difference is where prior to C99, you could only do this:
Which fills the first three elements, and zero fills the rest. In C99, you can set specific values to whatever you like.Code:int foo[10] = { 1, 2, 3 };
Giveing us an array containing:Code:int foo[10] = { 1, 2, 3, [1] = 5, [4] = 7 };
Quzah.Code:{ 1, 5, 3, 0, 7, 0, 0, 0, 0, 0 }