Aug 27, 2016

C Programming #83: designated intializers

C Programming #83: designated intializers

You have already know that array/structure variables can be fully or partially initialized. And when partially initialized only the beginning elements(array members, structure members) could be initialized. This limitation in C90 standard is removed by designated intializers that was introduced in C99 standard. This is whole new syntax that is used, which has some interesting application. This article examples designated intializers applied to array, structures, and array of structures.


designated intializers for array

Say we would we have integer array a of size 10. We would like to initialize the 3'rd element to 101 and 6th element to 105. It can be done as follows.

#include <stdio.h>
int main()
{
   int a[10] = {[2] = 101, [5] = 105};
   int i = 0;

   for(i = 0; i < 10; i++) {
      printf("a[%d]=%d\n", i, a[i]);
   }
   return 0;
}
a[0]=0
a[1]=0
a[2]=101
a[3]=0
a[4]=0
a[5]=105
a[6]=0
a[7]=0
a[8]=0
a[9]=0

designated range intializer for array

Say we have huge array of size 1000 and we would like to initialize 200-300 elements with value 5. Even the above method would not be concise, in such places range operator can be used. Below example demonstrates element 2-5 initialized with value 11.

#include <stdio.h>
int main()
{
   int a[10] = {[1 ... 4] = 11};
   int i = 0;

   for(i = 0; i < 10; i++) {
      printf("a[%d]=%d\n", i, a[i]);
   }
   return 0;
}
a[0]=0
a[1]=11
a[2]=11
a[3]=11
a[4]=11
a[5]=0
a[6]=0
a[7]=0
a[8]=0
a[9]=0

designated intializer for structure

Say we have following structure

typedef struct s_tag {
   char a,
   int b,
   float f,
}s_t;

Designated intializers for struct allows to initialize the elements as follows.

#include <stdio.h>
typedef struct s_tag {
   char a;
   int b;
   float c;
}s_t;
s_t s = {.c=1.1, .b=100, .a='x'};
int main()
{
   printf("s.a is %c, s.b is %d, s.c is %f\n", 
           s.a, s.b, s.c);
   return 0;
}
s.a is x, s.b is 100, s.c is 1.100000

Now struct and union follow similar syntax only difference being memory layouts. Same designated intializers could be extended to unions too.

designated intialisers for array of struct

Combining the 1st and 3rd method that is explained in this article. Designated intialisers for array of struct would look like this.

#include <stdio.h>
typedef struct s_tag {
   char a;
   int b;
   float c;
}s_t;
s_t s[2] = {[0].c=1.1, [1].b=100, [0].a='x', [1].a='y'};
int main()
{
   int i = 0;
   for(i = 0; i < 2; i++) {
      printf("index %d s.a is %c, s.b is %d, s.c is %f\n",
             i, s[i].a, s[i].b, s[i].c);
   }
   return 0;
}
index 0 s.a is x, s.b is 0, s.c is 1.100000
index 1 s.a is y, s.b is 100, s.c is 0.000000

Make sure that currently used c compiler is having C99 standard implemented.

No comments :

Post a Comment