-1
typedef struct
{
 int data;
int size;
} s1;

typedef struct
{
 char data;
 int size;
} s2;

typedef struct
{
 float data;
 char size;
} s3;

func(void *p)
{
      /*this should be generic to all structure.*/
      /* Need to do for removing duplicate codes*/
      /* p->data=1; p->size=0; this should be generic */
}
 int main()
{ s1 a;s2 b; s3 c;
   func(a);func(b);func(c);
 }

Here need to initialize this structure is random. Requirement is to keep "func" as a common function for all structure type.

Please suggest optimum method in C and not in C++

dandan78
  • 13,328
  • 13
  • 64
  • 78
  • 1
    Generic function won't succeed as you have different data types (casting is out) and you cannot use `memset` as you need to set value to `1`. – unalignedmemoryaccess Jan 27 '19 at 18:19
  • 1
    The only solution I can see is passing a second parameter for the type and casting based on that or making it a macro – Artyer Jan 27 '19 at 18:21

2 Answers2

0

A single function handling all three types will not work because the sizes and types of each member are different, even though the names are the same.

For example, storing the value 1 in the data field of each looks like this, assuming big endian byte ordering and IEEE 754 single precision representation for float:

a.data
---------------------
| 00 | 00 | 00 | 01 |
---------------------

b.data
------
| 01 |
------

c.data
---------------------
| 3f | 80 | 00 | 00 |
---------------------

So without knowing anything about the actual type there's no way to do exactly what you're looking for.

The closest you can come to what you want is to create a function for each type, then use a macro with _Generic to wrap which one gets called.

void func_s1(s1 *p)
{
    ...
}

void func_s2(s2 *p)
{
    ...
}

void func_s3(s3 *p)
{
    ...
}

#define func(p) _Generic((p), \
                         s1: func_s1, \
                         s2: func_s2, \
                         s3: func_s3)(&p)
dbush
  • 205,898
  • 23
  • 218
  • 273
0
typedef struct
{
    int data;
    int size;
} s1;

typedef struct
{
     char data;
     int size;
} s2;

typedef struct
{
     float data;
     char size;
} s3;

void func_s1(s1 p)
{
    printf("%s\n", __FUNCTION__);
}

void func_s2(s2 p)
{
    printf("%s\n", __FUNCTION__);
}

void func_s3(s3 p)
{
    printf("%s\n", __FUNCTION__);
}

void func_s1p(s1 *p)
{
    printf("%s\n", __FUNCTION__);
}

void func_s2p(s2 *p)
{
    printf("%s\n", __FUNCTION__);
}

void func_s3p(s3 *p)
{
        printf("%s\n", __FUNCTION__);
}


#define func(p) _Generic((p), \
              s1 *: func_s1p, \
              s2 *: func_s2p, \
              s3 *: func_s3p, \
              s1: func_s1, \
              s2: func_s2, \
              s3: func_s3)(p) \



int main()
{ 
    s1 a;s2 b; s3 c;
    func(&a);
    func(&b);
    func(&c);
    func(a);
    func(b);
    func(c);
}
0___________
  • 60,014
  • 4
  • 34
  • 74