const

closed account (ypLhURfi)
what is the difference.
for which serve.
1
2
3
4
5
6
#include <iostream>
using namespace std;
int main(){
	const int a=0;
	cout<<a;
}

1
2
3
4
5
6
#include <iostream>
using namespace std;
int main(){
	int a=0;
	cout<<a;
}
Last edited on
Your example is too simple to show any practical difference.
1
2
3
4
5
6
7
#include <iostream>
using namespace std;
int main(){
	const int a=0;
        // a = 1; // cannot!
	cout<<a;
}

1
2
3
4
5
6
7
#include <iostream>
using namespace std;
int main(){
	int a=0;
        a=1; // yay
	cout<<a;
}
In the first example, a is const. In the second, it isn't.

If you don't know what const means, it would be quicker and less effort for you to simply look it up, rather than ask us to re-type information that's already available for you to read.
closed account (ypLhURfi)
you block change value.
then what they are for?
not seem practical.
Last edited on
you block change value.

If you mean they stop you from changing the value, then that's exactly what they are for.

not seem practical.

Sometimes you don't want a value to change, like pi for example.

Read computerGeek's link.
Last edited on
closed account (ypLhURfi)
it is so that you do not change your own code.
I'm being stupid
it is so that you do not change your own code.

not exactly no. it's to prevent your code from inadvertently changing your code.

say you define this:

1
2
3
4
5
6
// mathematical pi:
double pi = 3.141;

// some other variable
double piVar = 42.0;


now let's say you come back and write some more code in a year's time and you need to change piVar from 42.0 to 43.0, but you haven't had much sleep and you're a bit hungover from the night before and you mistakenly type:

 
double pi = 43.0;   // oops changed the wrong variable 


your compiler will compile this quite happily. which is bad because you've just changed a fundamental constant of nature.
by declaring pi like this:
1
2
// mathematical pi:
const double pi = 3.141;

prevents silly mistakes like that, as now your compiler will moan and tell you you're trying to change something you have declared as constant.

it has lots of uses:
http://stackoverflow.com/questions/455518/how-many-and-which-are-the-uses-of-const-in-c
http://duramecho.com/ComputerInformation/WhyHowCppConst.html
Last edited on
closed account (ypLhURfi)
I think I get it. Are for not changing some data as pi.
Thanks for the help.
Last edited on
Topic archived. No new replies allowed.