Structures Question

Hi everyone, I'm a noob to C++ and could use some help with understanding one of the practice exercises in "Jumping into C++" by Alex Allain. This is a ch 11 (Structures) quiz question:



“4. What is the final value output by this code? ** Listed Below **

A. 5
B. 10
C. This code will not compile”


The answer is A. 5

What I do not understand is why the updateStruct (my_struct) function containing the my_struct.x value of 10 would not override the existing my_struct.x value of 5 in the main function.
Could someone please explain this to me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <iostream>
 
using namespace std;
 
struct MyStruct
{
int x;
};
 
void updateStruct (MyStruct my_struct)
{
my_struct.x = 10;
}
 
int main ()
{
MyStruct my_struct;
my_struct.x = 5;
updateStruct( my_struct );
cout << my_struct.x << '\n';
}
1
2
3
4
5
6
7
8
9
//Receives my_struct by copy. No change inside function
//would affect original value
//                       ↓↓↓↓↓
void updateStruct (MyStruct my_struct)

updateStruct( my_struct );
//             ↑↑↑↑↑
//Copies my_struct. Any changes to it inside function
//would have no effect on it 
Thank you so much!
probably because you're not writing java.

When you pass an argument, it creates a new object and copies it's value to the new object.

This is how you would do it correctly:

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
#include <iostream>

struct my_struct;
void set_x_to_ten(my_struct&);
 
struct my_struct
{
    int x;
};
 
inline void set_x_to_ten(my_struct &s) //pass by address
{
    s.x = 10;
}
 
int main ()
{
    using std::cout;
    using std::endl;
    
    my_struct tempstruct;
    tempstruct.x = 5;
    cout<< "tempstruct.x = "<< tempstruct.x<< endl;
    cout<< "Setting it to ten..."<< endl;
    set_x_to_ten(tempstruct);
    cout << "tempstruct.x now equals: "<< tempstruct.x << endl;
}


Pass the agument by address and you won't create a new object. Instead, you'll be using the same object as was passed.
Topic archived. No new replies allowed.