1

Using C99 I'm trying to do this within a function:

foo_t foos[4];
foos[0] = {1, {1,2}};

doesn't work. So I tried this...

foo_t foos[4];
foos[0] = (foo_t){1, {1,2}};

which works, but is it safe? Is there not perhaps a better way to do this?

3
  • It would help if you told us what the definition of foo_t is. Commented Apr 4, 2017 at 1:53
  • You could do: foo_t foos[4] = {{1, {1,2}}};. Though that is not exactly equivalent to what you have shown as it zero intialises the elements at indices 1-3 whereas your example does not. Commented Apr 4, 2017 at 1:58
  • In the actual code the foos[] array sits within an even larger array of structs (and contains additional lower level structs within itself), so I'd be unable to do a single assignment during declaration as the resulting excessive nesting would make the whole table an unintelligible mess. Commented Apr 4, 2017 at 17:19

1 Answer 1

1

The first case failed, because there no type associated with the expression (brace enclosed initializer)

Yes, the second code is safe, as long as the initializer list matches the expected types for the LHS. This is called compound literal, FWIW.

Quoting C11, chapter §6.5.2.5

A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.