constant in a member function to be assigned to global variable

How can we assign a constant in a member function to a const or non-const global variable (each with its own way explained)?
Last edited on
I don't understand what you mean for the "const case" because the point of const is that assignements aren't allowed.

For the non-const case, you can add a reference on the global variable and so use the reference to modify the variable.

However it's not recommended to use global variables for multiples reasons, so maybe you can copy your code here and explain what's the point of this so we can help you to find another better solution.
I'm not exactly sure what you are asking.

Does this code snippet cover your question? The assignment is in line 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

const int globalVal = 6;

class X
{
public:
    void foo()
    {
        const int counter = globalVal;
        for (int i = 0; i < counter; ++i)
        {
            std::cout << "Hello world!  Number " << i << std::endl;
        }
    }
};

int main()
{
    X myX;
    myX.foo();
    return 0;
}


Topic archived. No new replies allowed.