10

In C, why can't I do this:

arrayfn({1.0, 2.0, 3.0});

if arrayfn is some function that takes in one parameter of type double[] or double*, whichever. Trying this gives me a syntax error.

Is there a way that I could achieve something in C like this - generating and immediately passing an array known at compile time - that avoids having to spend a line of code pre-declaring and filling it?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Billy Smith
  • 273
  • 1
  • 5

1 Answers1

10

Short answer: You need to make use of a compound literal. Something like

 arrayfn( (double[]) {1.0, 2.0, 3.0} );

should do the job.


Some explanation

Coming to the part, why arrayfn({1.0, 2.0, 3.0}); did not work, because, without the syntax for compound literals, {1.0, 2.0, 3.0} is a brace enclosed initializer list. It does not denote an "object" which can be used as function argument. They are not "constant arrays", as you may have thought.

To add some more info, quoting C11, chapter §6.5.2.5, Compound literals

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thanks! It works. Bit weird that my immediate impulse was to run `(double*){1.0, 2.0, 3.0}`, which didn't do what I wanted it to do - but close enough! – Billy Smith Apr 22 '16 at 15:18
  • @user3528438: The `const` is optional; the compound literal is not a constant array unless you want it to be one. It can be modified by the code in the called function completely legitimately. – Jonathan Leffler Sep 04 '18 at 06:39