Reputation: 49
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):
Upvotes: 4
Views: 105
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 theregister
storage-class specifier.
Upvotes: 1
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