BoyOfJoy
BoyOfJoy

Reputation: 49

Implicit "declaration-in-instantiation" in C?

Is it possible to declare a variable implicitly in an initialization? Perhaps like so:

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

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

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

Advantages (in my eyes):

  1. No additional lines needed for explicit declaration
  2. Implicit variables are protected in the struct, no external access.

Upvotes: 4

Views: 105

Answers (2)

unwind
unwind

Reputation: 400129

No, that is not possible. The address-of operator requires an actual existing symbol as its argument.

The C11 draft says:

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

Upvotes: 1

M.M
M.M

Reputation: 141658

Yes it is possible, since C99. Your guess was very close; but it is required to provide a braced initializer even if you plan to assign another value later:

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

This feature is called compound literal. A compound literal is an lvalue.

Note that your testfunc contains an error though; since a has type void *, you cannot write *(test.a). You could either change S to have int *a; float *b;, or you'll have to cast at the point of writing, e.g. *(int *)test.a = 5;.

Upvotes: 5

Related Questions