1

let's say I have this global struct

struct input_shift_register
{
    bool not_used;
    int data;
    int *ptr_to_data;
};

and I would want to pass an instance of it in a function to modify its data

void share_data(input_shift_register shift) {
shift.data = 5;
}

This will only modify the local copy of the struct inside the function. How can I modify the "real" global struct instead? I am sorry this is probably very easy but I just can't find an answer online.

JCSB
  • 345
  • 2
  • 16

2 Answers2

5

You basically have 2 options.

  • Pass by reference
void share_data(input_shift_register& shift) {
  shift.data = 5;
}

This will make sure your function parameter is a reference(alias) bound to the function argument, hence you are dealing with the actual variable which is passed to the function at the calling site.

  • Pass by pointer
void share_data(input_shift_register* shift) {
  shift->data = 5;
}

This will make sure you are passing the address of the variable, hence at the calling site you should pass the address as the argument i.e. share_data(&shift_register);.

If you do pass by value(as in your code), it will simply pass a copy of the argument and the function will work with that copy, not with the actual variable.

For a detailed discussion have a look at the following.

What's the difference between passing by reference vs. passing by value?

aep
  • 1,583
  • 10
  • 18
2

Pass-by reference and Pass-by value are the two ways you can use for your specific needs.

However, you can also try this:

input_shift_register share_data(input_shift_register shift) 
{
    shift.data = 5;
    return shift;
}


input_shift_register var;
var = share_data(var)

If you define you function in this way, then the caller has a choice to either assign the returned value of the function to either the original var or to some other variable of the same struct.

This is the another way of doing the same thing. I wouldn't say it is best-optimized but it may suit some of the specific requirements.

abhiarora
  • 9,743
  • 5
  • 32
  • 57