Const problem

I am trying to use const with a function, and i thought you could but it isnt working, what am i doing wrong?

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
void Job(int &randNum, int &credits)
{
    int guess = 0;

    while(guess != -1)
    {
        cout << "Guess a number between 0 and 25" << endl;
        cout << "Enter -1 to quit" << endl;
        cout << ">";
        cin >> guess;

        for(int i = 0; i < 10; i++)
        {
            randNum = rand() % 25;
        }

        const int amountToGive = 5;
        const int amountToRemove = 3;

        if(guess < randNum + 5 && guess > randNum - 5)
        {
            AddCredits(credits, amountToGive);
            cout << "Correct! your current credit balance is " << credits << endl;
        }
        else if(guess == -1)
        {
            break;
        }
        else
        {
            RemoveCredits(credits, amountToRemove);
            cout << "Incorrect, you lose " << amountToRemove << " credits" << endl;
            cout << "Current balance " << credits << endl;
        }
    }
}


ERRORS:

||=== Build: Debug in Const (compiler: GNU GCC Compiler) ===|
C:\Users\thund_000\Desktop\Const\main.cpp||In function 'void Job(int&, int&)':|
C:\Users\thund_000\Desktop\Const\main.cpp|89|error: invalid initialization of reference of type 'int&' from expression of type 'const int'|
C:\Users\thund_000\Desktop\Const\main.cpp|56|error: in passing argument 2 of 'void AddCredits(int&, int&)'|
C:\Users\thund_000\Desktop\Const\main.cpp|98|error: invalid initialization of reference of type 'int&' from expression of type 'const int'|
C:\Users\thund_000\Desktop\Const\main.cpp|62|error: in passing argument 2 of 'void RemoveCredits(int&, int&)'|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
What you're trying to pass into the function isn't matching the function definition.
Variables can easily be promoted to const through a function call, but it's a compiler error to try to pass a reference of a const to a function that expects a non-const.

The definitions of your AddCredits and RemoveCredits should probably be passing the second argument as const int, not int&.

If that didn't help, post the function definitions for all pertinent functions.
Last edited on
ah ok thanks, I got it working now, it's been quite a while since i wrote any code.
Topic archived. No new replies allowed.