Search code examples
cfunctionstructparameter-passingcompound-literals

How to declare and pass a structure during function invocation?


It is very common to declare and pass a basic data-type variable during a function invocation, can we achieve something similar with the structures ? Below code explains my question better.

struct s 
{
    int i;
    char c;
};

void f(int i)
{
    return;
}

void g(struct s s1)
{
    return;
}

int main()
{
    int i = 5;  // possible
    struct s s1 = {1, 'c'}; // possible

    f(i);   // possible
    g(s1);  // possible

    f(5);   // possible
    g({1, 'c'});    // not possible, is there any alternative way ?

    return 0;
}

Solution

  • First of all, as a rule of thumb you should avoid passing structs by value, because that's slow and takes up lots of memory. A better interface would be:

    void g (struct s* s1)
    ...
    g(&s1);
    

    To answer the question, you may use a compound literal:

    g( (struct s){1, 'c'} );