Implicit declaration-of-copy in C?

Is it possible to declare a variable implicitly during initialization? Perhaps so:

struct S
{
  void *a;
  void *b;
};

struct S test = {&(int), &(float) };

void testfunc (void)
{ 
  *(test.a) = -2;
  *(test.b) = 1.3;
}

Advantages (in front of my eyes):

  • No extra lines to explicitly declare
  • Implicit variables are protected in the structure, without external access.
+4
source share
2 answers

Yes, possibly starting with C99. Your hunch was very close; but you need to provide a simplified initializer, even if you plan to assign a different value later:

struct S test = { &(int){0}, &(float){0} };

This function is called a composite literal . An adjacent literal is an lvalue.

, testfunc ; a void *, *(test.a). S int *a; float *b;, , . *(int *)test.a = 5;.

+5

, . address-operator .

C11 :

& , [] *, lvalue, , register .

+1

Source: https://habr.com/ru/post/1653107/


All Articles