-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct_as_argument.cpp
More file actions
50 lines (38 loc) · 1.26 KB
/
struct_as_argument.cpp
File metadata and controls
50 lines (38 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
using namespace std;
// Define the struct
struct Student {
string name;
int age;
float marks;
};
// Pass struct by value (makes a copy)
void displayByValue(Student s) {
cout << "\n[By Value] Name: " << s.name << ", Age: " << s.age << ", Marks: " << s.marks << endl;
}
// Pass struct by reference (no copy, changes will affect original)
void displayByReference(Student &s) {
cout << "\n[By Reference] Name: " << s.name << ", Age: " << s.age << ", Marks: " << s.marks << endl;
// Let's change something
s.marks += 5; // Adding bonus marks
}
// Pass struct as const reference (safe read-only)
void displayConstRef(const Student &s) {
cout << "\n[Const Reference] Name: " << s.name << ", Age: " << s.age << ", Marks: " << s.marks << endl;
}
int main() {
Student s1;
// Input values
cout << "Enter name: ";
cin >> s1.name;
cout << "Enter age: ";
cin >> s1.age;
cout << "Enter marks: ";
cin >> s1.marks;
// Call different functions
displayByValue(s1);
displayByReference(s1); // This changes s1.marks
displayConstRef(s1); // Safe read-only
cout << "\nUpdated Marks after reference call: " << s1.marks << endl;
return 0;
}