bengbeng
bengbeng

Reputation: 21

Pass a Struct to a Function

When you pass a struct to a function, is it pass by value (similar to regular variables where the value gets cloned), or is it pass by reference (similar to arrays where the actual variable is passed)? Can you give an example.

Upvotes: 2

Views: 4192

Answers (3)

Christophe
Christophe

Reputation: 73577

A struct is passed by value:

struct S {
    int a,b; 
};

void f(struct S s) {
    printf("%d\n", s.a+s.b); 
    s.a = 0;   /* change of a in local copy of struct  */
}

int main(void) {
    struct S x = { 12,13};
    f(x);
    printf ("Unchanged a: %d\n",x.a);
    return 0;
}

Online demo

Upvotes: 4

Ely
Ely

Reputation: 11174

In C everything is pass by value, even passing pointers is pass by value. And you never can change the actual parameter's value(s).

That is from K&R by the way. And I recommend to read that book. Saves you many questions you might post in the future.

Upvotes: 4

Marcin Możejko
Marcin Możejko

Reputation: 40516

You are passing it by value. Everything in a structure is copied.

Upvotes: 1

Related Questions