Reference Variables I really dont understand

Hello everyone,

Im having a difficulty of what is the use of reference variables and how to use it specially in gaming can someone give me a brief explanation to it...I study advanced in c++ before going to college and Im new to C++ im not even a month so please help me..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

using namespace std;

void getScore(int& score);
void printGrade(int score);

int main()
{
    int courseScore;

    getScore(courseScore);
    printGrade(courseScore);

    return 0;
}

void getScore(int& score)
{
   cout << "Enter score: ";
   cin >> score;
   cout << "Score is: " << score << endl;
}

void printGrade(int cScore)
{
   cout << "Your grade is: ";

   if(cScore >= 90)
     cout << "A." << endl;
   else if(cScore >=80)
     cout << "B." << endl;
   else if(cScore >= 70)
     cout << "C." << endl;
   else if(cScore >= 60)
     cout << "D." << endl;
   else
     cout << "F." << endl;
}


This as for instance, what if there will be no reference parameter and also is there any alternative way to do same output without using the reference parameter?
If you want to avoid references, you could replicate the behavior with a pointer. However, there is no guaranteeing that pointer is non-NULL or even valid. The point of a reference parameter is that you will actually be modifying the parameter you pass in, instead of simply getting a copy of its value to work with.
A reference is used here so that changes to score inside getScore will also change courseScore in main.
You can write the program without references by using a return value instead.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...

int main()
{
    int courseScore;

    courseScore = getScore();
    printGrade(courseScore);

    return 0;
}

int getScore()
{
   cout << "Enter score: ";
   cin >> score;
   cout << "Score is: " << score << endl;
   return score;
}

...

Last edited on
Topic archived. No new replies allowed.