### Can Somebody Explain How This Works?

Hey! I am prepearing for the test and I
would like to know how these two codes
are working step by step.

 ``12345678910111213141516171819202122232425262728293031`` ``````#include using namespace std; int g, p = 1; void p1(int m1, int &n1) { m1 = m1*3; n1 = n1*3; p = p*3; } int func (int & m3, int n3) { int p = m3; p1 (m3, p); m3 = p; return g + n3; } int main () { int a, b; cin >> a >> b; for (g = a; g<=b; g++) { cout << func (p, g)<

 ``12345678910111213141516171819202122232425262728`` ``````#include using namespace std; int g = 5; int f(int& x, int& y, int z) { if (x > y){ y = y + 2; x = g - y; g = z + 1; return z - 1; } else{ g =g + x; y = x - z; x = z + 1; return g - y; } } int main () { int x, y, z; cin >> x >> y >> z; cout << f (y, g, x) <<" "<< x <<" "<< y <<" "<
That's pretty basic stuff.

Did you manage to get to the end of a C++ course and not learn how to call a function an pass parameters by value and by reference?
Piece of code no.1 has so many errors in. Where did you get this code? :s
I would start by making the variables more easily human readable.

If all the variables are letters then it can become hard to keep track of them when you pass the variables around functions.
Last edited on
Both programs are basically a test of how well you understand variable scope and pass-by-reference vs. pass by value. The things that look like "errors" are intentional. Remember that a parameter which is passed by value won't be changed if assigned to, and won't actually affect anything unless it is used in the calculation of the return value. However, a parameter passed by reference will be changed if it is assigned to.

This is an extremely simple example:
 ``12345678910111213141516`` ``````void func(int &byRef, int byVal) { byRef += byVal; byVal += byRef; } int main() { int byRef = 1; int byVal = 5; func(byRef, byVal); std::cout << "Passed by reference: " << byRef << std::endl; std::cout << "Passed by value: " << byVal << std::endl; return 0; }``````

You should easily be able to see why the output is:
 ```Passed by reference: 6 Passed by value: 5```
This program works, however I have no clue what its supposed to accomplish lol.
Topic archived. No new replies allowed.