2

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.

2
  • By default, it is pass by value, unless you pass a pointer to the structure. Commented Apr 10, 2016 at 21:49
  • a structure being passed to a function will always arrive at the function as a pointer to the structure, actually, a cloned pointer to the structure. Note: arrays are NOT passed to a function, rather an address of the array is passed, actually a clone of the address of the array. Commented Apr 12, 2016 at 20:36

3 Answers 3

4

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.

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

Comments

4

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

Comments

1

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

3 Comments

Can you give an example?
@bengbeng write your own example. you know how to make a function. use struct S as parameter instead of int or whatever.
Struct is implemented in a way, that a block of a memory is allocated to store it's members. When you pass a struct as argument - you may think about it as copying this block of a memory to a function.

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.