#include <iostream>
usingnamespace std;
// Increases value of variable pointed by ptr by one and returns its double
int Func (int* ptr)
{
*ptr = *ptr + 1;
return ((*ptr)*2);
}
int main ()
{
int a=3;
cout << Func (&a) << " " << a << endl;
cout << a << endl;
return 0;
}
I think when we call Func () (in line 16) value of a is changed to 4, so output should be such as the following:
8 4
4
But the output is:
8 3
4
Can you explain for me why?
Thanks for your helps.
In this case the value of a is passed into << function before Func is called. Generally it's not a good idea to use somewhere a variable that has been already modified on the same line. The behavior may be unexpected or undefined.
The first one prevents the method from changing the values of any variables in the class.
The second one means that the function returns a constant value(it is really only useful when returning pointers to constant memory).