Wrong results while using pointers

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# include <iostream.h>
void square(int&,int&);
void cube(int&,int&);
int main()
{
int a=3;
int b=4;


void (*ptr) (int&,int&);


ptr=cube;
ptr(a,b);
cout<<a<<endl<<b<<endl;
ptr=square;
ptr(a,b);
cout<<a<<endl<<b<<endl;

return 0;
}
void square (int & s,int & d)
{
s*=s;
d*=d;
}

void cube (int & s,int & d)
{

int temp;
temp=s;
s*=s;
s*=temp;

temp=d;
d*=d;
d*=temp;
}


The output is 27,64,729,4096.

The correct output should be 27,64,9,16
cant really figure out whats wrong.
Help ?
Last edited on
Kind of an odd way to just call the function. Why not call cube and square directly instead of through ptr?

Anyways, you're passing references so your modifying the integers that you pass. This generally isn't preferred but you can just reset the variable values: http://codepad.org/k04mdR5F
Was just studying pointers so tried it,i know calling the function directly would be more sensible.

Anyway that explains the problem , silly of me not to see.
Thanks.
Topic archived. No new replies allowed.