c++cfunction

How to pass a constant array literal to a function that takes a pointer without using a variable C/C++?


If I have a prototype that looks like this:

function(float,float,float,float)

I can pass values like this:

function(1,2,3,4);

So if my prototype is this:

function(float*);

Is there any way I can achieve something like this?

function( {1,2,3,4} );

Just looking for a lazy way to do this without creating a temporary variable, but I can't seem to nail the syntax.


Solution

  • You can do it in C99 (but not ANSI C (C90) or any current variant of C++) with compound literals. See section 6.5.2.5 of the C99 standard for the gory details. Here's an example:

    // f is a static array of at least 4 floats
    void foo(float f[static 4])
    {
       ...
    }
    
    int main(void)
    {
        foo((float[4]){1.0f, 2.0f, 3.0f, 4.0f});  // OK
        foo((float[5]){1.0f, 2.0f, 3.0f, 4.0f, 5.0f});  // also OK, fifth element is ignored
        foo((float[3]){1.0f, 2.0f, 3.0f});  // error, although the GCC doesn't complain
        return 0;
    }
    

    GCC also provides this as an extension to C90. If you compile with -std=gnu90 (the default), -std=c99, or -std=gnu99, it will compile; if you compile with -std=c90, it will not.