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
4/7/2021 1:58:57 PMSlick
7 AnswersNew Answer
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.
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.
Either make it global or pass by reference.
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.
I appreciate all the info get and Hima. Thanks for taking the time to explain
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.