why can I still give const value a new value

116 views Asked by At

enter image description hereThe book said I cannot change the value of const once I gave it a number, but it seems I can still give it a number even if it was given.

#include<iostream>
using namespace std;
const int fansc(100);
cout<< fansc << endl; //output:100
int fansc(20);
cout<< fansc << endl;//output:20
1

There are 1 answers

4
paxdiablo On BEST ANSWER

The C++ code you gave won't compile, and rightly so. A const variable(a) is, well, ... constant. The error is shown in the following program and transcript:

#include <iostream>
using namespace std;
int main() {
    const int fansc(100);
    cout << fansc << endl;
    int fansc(20);
    cout << fansc << endl;
}
pax> g++ --std=c++17 -Wall -Wextra -Wpedantic -o prog prog.cpp
prog.cpp: In function ‘int main()’:
prog.cpp:6:9: error: conflicting declaration ‘int fansc’
    6 |     int fansc(20);
      |         ^~~~~
prog.cpp:4:15: note: previous declaration as ‘const int fansc’
    4 |     const int fansc(100);
      |               ^~~~~

That leaves the Anaconda bit that you mention in a comment. I have little experience with that but it seems to me the only way that would work is if the second fansc definition was somehow created in a different scope to the first. In real C++ code, that would go something like:

#include <iostream>
using namespace std;
int main() {
    const int fansc(100);
    cout << fansc << endl;
    { // new scope here
        int fansc(20);
        cout << fansc << endl;
    } // and ends here
    cout << fansc << endl;
}

And the output of that is:

pax> g++ --std=c++17 -Wall -Wextra -Wpedantic -o prog prog.cpp && ./prog
100
20
100

(a) Yes, I know that's a self-contradiction :-)