Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

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

2 answers 190 views
2 answers 158 views
1 answer 144 views
1 answer 149 views
1 answer 87 views
...