C++ Pass Structures to a Function

🧩 C++ Pass Structures to a Function

In C++, a structure (struct) can be passed to a function in three main ways:

  1. Pass by value

  2. Pass by reference

  3. Pass by pointer

Each method has different behavior and use cases.


πŸ”Ή 1. Pass Structure by Value

A copy of the structure is passed.
Changes inside the function do NOT affect the original structure.

struct Student {
int id;
string name;
};

void show(Student s) {
s.name = "Changed";
cout << s.name << endl;
}

int main() {
Student s1 = {101, "Amit"};
show(s1);
cout << s1.name; // Amit (unchanged)
}

βœ” Safe
❌ Slower for large structures


πŸ”Ή 2. Pass Structure by Reference (Recommended)

The function works on the original structure.

void update(Student &s) {
s.name = "Changed";
}

int main() {
Student s1 = {101, "Amit"};
update(s1);
cout << s1.name; // Changed
}

βœ” Fast
βœ” No copy
βœ” Most commonly used


πŸ”Ή 3. Pass Structure by Pointer

Address of the structure is passed.

void update(Student *s) {
s->name = "Changed";
}

int main() {
Student s1 = {101, "Amit"};
update(&s1);
cout << s1.name; // Changed
}

βœ” Flexible
❌ Needs dereferencing (->)


πŸ”Ή 4. Read-Only Structure (const Reference)

Use when you don’t want to modify the structure.

void display(const Student &s) {
cout << s.name;
}

βœ” Safe
βœ” Efficient


πŸ”Ή 5. Pass Array of Structures to a Function

void printStudents(Student s[], int size) {
for (int i = 0; i < size; i++) {
cout << s[i].name << endl;
}
}

Call:

Student students[2] = {
{101, "Amit"},
{102, "Neha"}
};

printStudents(students, 2);


πŸ”Ή 6. Return Structure from a Function

Student createStudent() {
Student s;
s.id = 201;
s.name = "Rahul";
return s;
}

βœ” Modern compilers optimize copying (RVO)


πŸ” Comparison

Method Original Modified? Performance
By value ❌ No Slower
By reference βœ” Yes Fast
By pointer βœ” Yes Fast

❌ Common Mistakes

void fun(Student &s);
fun({101, "Amit"}); // ❌ cannot bind to non-const reference

βœ” Correct:

void fun(const Student &s);

πŸ“Œ Summary

  • Structures can be passed by value, reference, or pointer

  • Pass by reference is usually best

  • Use const & for read-only access

  • Arrays of structures are passed like arrays

You may also like...