C++ Pass Structures to a Function
Pass Structure to a Function
You can also pass a structure to a function.
This is useful when you want to work with grouped data inside a function:
Example
    struct Car {
  string brand;
  int year;
};
void myFunction(Car 
    c) {
  cout << "Brand: " << c.brand << ", Year: " << c.year << "\n";
    }
    
int main() {
  Car myCar = {"Toyota", 2020};
  
    myFunction(myCar);
  return 0;
}
Try it Yourself »
Note: Since the structure is passed by value, the function gets a copy of the structure.
This means that the original data is not changed.
Pass by Reference
You can also pass a structure by reference, using &.
This allows the function to modify the original data:
Example
    struct Car {
  string brand;
  int year;
};
void updateYear(Car& c) {
  
    c.year++;
}
    
int main() {
  Car myCar = {"Toyota", 2020};
  
    updateYear(myCar);
  cout << "The " << myCar.brand << " is now from 
    year " << myCar.year << ".\n";
  return 0;
}
Try it Yourself »
Tip: Use reference if you want the function to change the structure's data, or to avoid copying large structures.
 
