0

I'm little confused about two types of i came across like if int a=0, what does it "&ref=a" refers to and what "ref=&a" this thing refers to?

do these serves the same purpose of holding address of variable?

Srikanth
  • 38
  • 6
  • 2
    Those are not complete declarations. I assume you mean `int &ref = a;` and `int *ref = &a;`. The difference is the first one is a reference to `a` and the second one is a pointer to `a`. Similar but very different things. A pointer contains a memory address, yes. A reference is just an alias to the thing it refers to, but it is *commonly* implemented using a pointer in most compilers. – Remy Lebeau Apr 07 '20 at 03:26
  • Please edit your question and clarify what `&ref = a;` and `ref = &a;` are referring to. I suspect it is as @RemyLebeau suggests above. Also when you edit, if you encluse the code portions in *back ticks*, e.g. `\`` -- it will format in fixed width. – David C. Rankin Apr 07 '20 at 03:54
  • 2
    Does this answer your question: [What are the differences between a pointer variable and a reference variable in C++?](https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in) – Miles Budnek Apr 07 '20 at 05:25

2 Answers2

0

See this

int a=10;
int &ref=a;
std::cout<<ref;

it will print 10

int a=10;
int *ref=&a;
std::cout<<ref;

it will print address of a, if you want value you should put like this *ref that is you should dereference it.

#include<iostream>
#include<fstream>

void fun(int &var)
{
    var=100;
}

int main()
{
    int a=10;
    fun(a);    //no need & here
    std::cout<<a;
    return 0;
}

and see this

#include<iostream>
#include<fstream>

void fun(int *var)
{
    *var=100;
}

int main()
{
    int a=10;
    fun(&a);    //need & here
    std::cout<<a;
    return 0;
}
srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25
0

&ref=a : It is the reference variable means it's is the another name for existing variable. It can be used like normal variables.Memory management of references left up to compiler

*ref=&a : It is the pointer variable it holds the address of another variable. Pointers are used to store and manage the addresses of dynamically allocated blocks of memory.

And the my answer is YES, Both should serves the same purpose in holding variable because in most compilers the reference can thought as constant pointer itself.

itsAPK
  • 103
  • 1
  • 10