### Thread: Can somebody explain how we got 3, 15, 45 for x, y, z?

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
2
Rep Power
0

#### Can somebody explain how we got 3, 15, 45 for x, y, z?

#include <stdio.h>
#include <stdlib.h>

int stuff(int a, int *b);
int things(int L, int *M);

int main(){
int x = 3, y = 5, z = 0;
z = stuff(x, &y);
printf("%d\t%d\t%d\n", x, y, z);
return 0;
}

int stuff(int a, int *b){
if (a % 2) {
*b = things(a, b);
return a * *b;
}else
return a + *b;
}

int things (int L, int *M){
*M = L * *M;
return *M;
}
2. Remember the &y in stuff mean y is sent by reference so whatever happens to the formal parameter in the function affects the value of the actual parameter.
3. The simplest method for determining how this code works is to step it in your debugger while watching the variables. That will be far more instructive than any explanation that might be given here.

Besides that, you have left the question rather too far open, necessitating any answer to exhaustively describe the execution of the code; something the debugger will be far better for, and which to be honest is a) too much work, b) in danger of doing your homework for you. Instead you might explain why you thing the results should perhaps be something else, and why you think that. That way the answer can put you straight on your specific misunderstanding.
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
2
Rep Power
0

#### This is my explanation; would appreciate any thoughts

main function:
On the stack > we got x = 3, y =5, z =0
main calls stuff and passes x and &y
x =3
&y is the address of y; ex. 0x1000; y = 5;

stuff function
On the stack > we got a = 3, b = &y, hence *b = 5
3 modules 2 = 1 condition is true
stuff calls things

things function
On the stack > we got L = 3, M = &y, hence *M = 5
*M = L * *M
*M = 3 * 5 = 15

things function return 15 to stuff; *b is now 15

stuff function return a + *b = 3 * 15 = 45 to main

Now main have x = 3, y =15, z = 45;

Is my logic right?

Originally Posted by bullet
Remember the &y in stuff mean y is sent by reference so whatever happens to the formal parameter in the function affects the value of the actual parameter.
5. Originally Posted by c0ldhand
main function:
On the stack > we got x = 3, y =5, z =0
main calls stuff and passes x and &y
x =3
&y is the address of y; ex. 0x1000; y = 5;

stuff function
On the stack > we got a = 3, b = &y, hence *b = 5
3 modules 2 = 1 condition is true
stuff calls things

things function
On the stack > we got L = 3, M = &y, hence *M = 5
*M = L * *M
*M = 3 * 5 = 15

things function return 15 to stuff; *b is now 15

stuff function return a + *b = 3 * 15 = 45 to main

Now main have x = 3, y =15, z = 45;

Is my logic right?
agree with this logic its correct