0

Why doesn't the function assign new values?

I'm making a small fraction problem solver. I put a function in to change the given fractions to equal fractions with the same GCD. Printing out values inside the function work just fine, but the changes don't seem to take place outside of the function. What am I doing wrong here? https://code.sololearn.com/cMApyS7MP8kQ/?ref=app

7th Apr 2021, 1:58 PM
Slick
Slick - avatar
6 Respostas
+ 6
In this way the compiler copies the given memory. You need the parameter holding/sharing the same memory address. Two ways to do that: 1. Use passing by pointer: give the &argument (pointer to argument) instead of argument, make the function take *parameter (for example, fraction frac1 is fraction *frac1 (you can use different spacing around the star)) and use *parameter instead of parameter inside the function. 2. Use passing by reference: just change, for example, fraction frac1 to fraction &frac1 (again, you can use different spacing). For explanation of the first variant see https://www.sololearn.com/learn/CPlusPlus/1643/ and for short information about the second variant see the most liked comments at the third page of it.
7th Apr 2021, 2:14 PM
#0009e7 [get]
#0009e7 [get] - avatar
+ 3
Slick, I would recommend you using pointers/references parameters only when it is needed. If you always use them, the data can be corrupted/spoiled/(just changed when you need to save and use the real data after the function calling) by the function, and thus be even dangerous.
7th Apr 2021, 2:23 PM
#0009e7 [get]
#0009e7 [get] - avatar
+ 3
Either make it global or pass by reference.
7th Apr 2021, 2:25 PM
Hima
Hima - avatar
+ 3
Hima is right. Two notes about using global variables: use the global variable like it is in defined in every namespace of a program (except included libraries; actually compiler/computer actually thinks that when executing the code); you can define a variable with the same name in a function, class, namespace, etc. and use it instead and use :: before the name of the variable when you need to use the global variable.
7th Apr 2021, 2:30 PM
#0009e7 [get]
#0009e7 [get] - avatar
+ 2
I appreciate all the info get and Hima. Thanks for taking the time to explain
7th Apr 2021, 2:32 PM
Slick
Slick - avatar
+ 1
Thats it, just switched to pointers and works perfect. Thanks! Also, is it just smarter to usually always use pointers? I see more and more stuff like this where using pointers is just all around better.
7th Apr 2021, 2:20 PM
Slick
Slick - avatar