What is the difference between a pointer and reference in C++

1 Answer

0 votes
#include <iostream>

int main()
{
    int x = 7;
    int y = 83;
    
    // pointer can declare without init
    int* ptr;
    ptr = &x;

    // pointer can retarget
    ptr = &y;
    *ptr = 100;
    std::cout << x << " " << y << "\n";
    
    // reference must be init
    int& ref = x;
    
    // reference can't retarget
    // ref = &y; // error: invalid conversion from 'int*' to 'int'
    
    ref = y; // this code stores the value of y (100) into x
    std::cout << x << " " << y << "\n";
    
    // pointer can set to null
    ptr = nullptr;
    
    // reference can't set to null
    // ref = nullptr; // error: cannot convert 'std::nullptr_t' to 'int' in assignment
}


/*
run:

7 100
100 100

*/

 



answered Sep 28, 2024 by avibootz

Related questions

...