jeudi 9 septembre 2021

C++ Pointers assignment gives unexpected(?) results

int* snap = nullptr;
int last = -1;   
void func(int* md){
        if(snap!=nullptr) {
            last = *snap;
        }
        snap = md;
        cout<<last<< " "<<*snap<<endl;
    }
    
    int main() {
        
        for(int i =0;i<10;i++) {
            int arg = i;
            func(&arg);
        }
        return 0;
    }`

Output

-1 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8

Shouldn't the 'last' variable have the previous iteration's value of 'snap'. But the values are equal. What am I doing wrong here?

Aucun commentaire:

Enregistrer un commentaire