What is the difference between a reference variable ( eg int& ref) and a pointer variable ( int*pointer ).


There are no reference variables in C. They were introduced in C++. So your question is not valid for the CS50 course.

Nevertheless the difference is that you can use a reference variable as normal variable, instead having to deal with pointers. So if a function accepts a reference variable you can do this:

#include <stdio.h>

void swap(int &a, int &b)
    int tmp = a;
    a = b;
    b = tmp;


int main(void)
    int a = 5;
    int b = 10;

    printf("a=%d b=%d\n", a, b);

    swap(a, b);

    printf("a=%d b=%d\n", a, b);

    return 0;

Which prints:

a=5 b=10
a=10 b=5

Notice that you don't have to create pointers and pass those in the function. You use a and b as normal variables.

There is also the benefit that since you pass a reference, there is no need for a copy of the variable to be created, and that saves time and space.

Also reference variables are safer that pointer variables, since you always have to initialize them the moment you declare them.

So if I try this:

int &c;

I get the following error:

error: ā€˜cā€™ declared as reference but not initialized
     int &c;

Anyway, if you want to learn more check this site: C++ References and also this much more complete answer in StackOverflow: What are the differences between a pointer variable and a reference variable in C++?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .