1

Is this possible in C or C++? I have a function with the following declaration:

int foo(double*)

And I am trying to do something like this:

foo([] = {1.0, 2.0, 3.0, 4.0});

I know that I can create an array separately, but I am curious if I can do it that way.

Thanks.

2
  • 1
    What happened when you tried it ? Commented Dec 6, 2013 at 23:24
  • Syntax error. syntax error : '=', using VS 2012. Commented Dec 6, 2013 at 23:26

2 Answers 2

4

In C: use C99 compound literals:

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

In C++: (I hate "C/C++" questions!) - I tried this and used C++11 initializer lists in a similar way. However, I'm not entirely confident whether this is legal or results in undefined behavior:

foo(&(std::vector<double> { 1, 2, 3, 4 })[0])

Anyone could confirm this? (compiles with no warnings, runs... that doesn't mean anything, though.)

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

3 Comments

There should be restriction not to tag same question with both C and C++ tag together.
What a coincidence! :)
0

Yes you can do that by compound literals. C99 allows this feature.

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

In this example, the compound literal creates an array (on the fly) containing the four floats.
You may also write this

  foo((double[4]){1.0, 2.0, 3.0, 4.0});   

2 Comments

The paranthesis don't match.
@piokuc; That's because I copied OP's code and did some changes to it instead of typing :)

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.