Here is my first tutorial, not sure how good it will be for this site.
Const (constants) type restrict the usage of that variable so that it value for example cannot be altered which is good for values of pi, you do not want that changed from 3.142 to 5, because then your circle will just not look the same!!.
There are a couple of places to put a const type in a variable declaration.
Code:
int normalInt = 10;
const int constInt = 30;
the first normalInt value is 10 and can be altered but the const int cannot not.
For pointers it is more fun,
Code:
const int * pConst = &constInt;
Here the pConst is pointing to a const int value, but its pointing to place (the memory location of the variable) can change.
Code:
int * const pConst = &normalInt;
Slightly different the value that is pointed to can change, since it is a normal int value, but the value within the pConst cannot e.g. the memory location to where it is pointing, so it will always point to the same variable.
Code:
const int * const pConstConst = &constInt;
Here is more fun, it is a const int (cannot change the value) const pointer (cannot change where pointing to) pointer!!.
You can also place const within the functions definition
Code:
const int returnValue(const int value1) const;
Here in order
1. Cannot change the return'd value, unless you assign it to a variable.
2. Cannot change the parameters value.
3. Cannot change the "this" class variables.
For example for the first one,
Code:
int returnedValue = returnValue(10);
The returnedValue can be changed but if you did
would produce an error because you are trying to increment a const int.
The second one, the parameter const is similar in that you cannot alter the value passed
Code:
const int returnValue(const int value1)
{
value1= value1+10;
return value1;
}
Cannot do this, because value1 cannot be altered.
The last is more fun, where you cannot alter the values within "this" class. For example
Code:
class AClass
{
private :
int var1;
public:
AClass() { var1 = 10};
int returnValue(int value1) const;
};
int AClass::returnValue(int value1) const
{
// cannot do this !!. var1 is part of "this class"
var1 = var + 1;
return var1;
}
I do really like to have any feedback regarding any tutorial, just reply or PM me.. glad to help, better to share knowledge.
Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum