Function and Pointer

Hello everyone, I have a fragment code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace 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.
i compiled that code, the output is:

8 4
4

i'm curious how can you get that result?

btw, if you wanna pass the address of the variable, i suggest the following:
1
2
3
4
5
6
7
8
9
void test_addr (int &n) {
//...
}

int main () {
int j;
test_addr (j);
//...
}


the above function is better, it's clearer for me, for using it as the "pointer-accepts" function :) e.g:

1
2
3
int test_point (int *p) {
return (*(p)*7);
}


oh yeah, i have a question for functions :) for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class BankAccount
{
public:
BankAccount(int iNumber, double dSaldo = 0);
BankAccount(const BankAccount& bankAccount);
void Deposit(double dAmount) {m_dSaldo += dAmount;}
void Withdraw(double dAmount) {m_dSaldo -= dAmount;}

//i'm talking about this two lines
/***********************************/
int GetNumber() const {return m_iNUMBER;}
double GetSaldo() const {return m_dSaldo; }
/***********************************/
private:
const int m_iNUMBER;
double m_dSaldo;
};


is it the same thing if i use this:

1
2
const int GetNumber() {return m_iNUMBER;}
const double GetSaldo() {return m_dSaldo; }


if it's not, then what's the purpose of doin' that?
1
2
int GetNumber() const {return m_iNUMBER;}
double GetSaldo() const {return m_dSaldo; }


It is NOT the same as this:

1
2
const int GetNumber() {return m_iNUMBER;}
const double GetSaldo() {return m_dSaldo; }


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).
Topic archived. No new replies allowed.