function question?

I am looking at reviewing some code and confused as how the sample code works below without using "passing parameters by reference". Does anybody got an idea? The code below is an example. The correct answer according to the code I am looking at should be x=2,y=6, and z=14.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include <cstdio>   //corrected


int x=1, y=3, z=7;

void duplicate (int a, int b, int c)
{
  a=a*2;
  b=b*2;
  c=c*2;
}

int main ()
{
  
  duplicate (x, y, z);
  printf("The answer is %i and %i and %i",x,y,z);
  
  return 0;
}
Last edited on
It would not even compile: it includes unneeded iostream and forgot to include <cstdio> for printf.

Ant it outputs 1, 3, 7 as duplicate essentually doing nothing. Compiler even throws its away as useless.
I am not able to figure out the code I am looking at work. The answer is x=2, t=6, and z=14. I do not know why it works.
Last edited on
The answer is x=2, t=6, and z=14


No. No it is not.

I do not know why it works.
It's not. It does not and cannot possibly work as you described.

http://ideone.com/pmDqh6
http://coliru.stacked-crooked.com/a/f1065c25b18cf1bd
http://melpon.org/wandbox/permlink/tfE27nQS2hcY3ycd
http://cpp.sh/6ida
Is there something I am missing? The code I am looking at is written in C. How can I get the answers(x=2, t=6, and z=14) by using a function and without "passing parameters by reference"?
Where did you copy this code from? The only way it could work as you describe is if you made a typo in the function "duplicate()" and instead it should be:
1
2
3
4
5
6
void duplicate (int a, int b, int c)
{
  x=a*2;
  y=b*2;
  z=c*2;
}


In which case there is nothing magical about it, it's just showing you global variables.
The top code should have been:

void duplicate (int a, int b, int c)
{
x=a*2;
y=b*2;
z=c*2;
}
like Computergeek01 pointed out! :)
Topic archived. No new replies allowed.