Const redeclared in main() with new value?

What happens if you redeclare a variable that is already static and declared outside of main() kind of like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

const int amount = 50;

int main()
{

int otherAmount = 0;
int amount = 25;

otherAmount %= amount;

{


I hope I'm clear enough, and any help is much appreciated. Trying to learn this stuff!
Does it just add the two together and then find the remainder of the sum or?
I'm having trouble finding this answer anywhere.
Last edited on
This is known as "shadowing". In the scope where you have created another variable with the same name, that new one gets used. You can still reach the global one. Here's some example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

const int amount = 50;

int main()
{
    
    cout << "Amount = " << amount << '\n';
    int amount = 25;
    cout << "Amount = " << amount << '\n';
    amount++; // changes local value
    cout << "Amount = " << amount << '\n';
    cout << "Global Amount = " << ::amount << '\n';  // global value unchanged
}

Topic archived. No new replies allowed.