Page 1 of 1

Using Constant explanation on how/where to use const Rate Topic: -----

#1 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 311
  • View blog
  • Posts: 1,515
  • Joined: 16-May 09

Posted 27 January 2010 - 12:38 PM

*
POPULAR

Preface
  • Defining Functions and Variables
  • Pointers
  • Different ways of passing arguments
  • An understanding of inline functions (for last example)
  • OOP (helps alot, specially in last example)
In C, there is #define with which you can define constant values, which is replaced by the preprocessor. This can benefit you when you want to use a value which is not meant to change at all... C++ has a feature to replace this usage of #define, it is called const, and the basic syntax is like the following:
const int ci = 5;

In the above single line of code, I defined an int, but what is that const keyword? it changes the normal int definition into a constant int definition. Which means the value of ci cannot be edited at all.
If you try to change the value of ci along the program, you will get a compile error. Isn't that nice? you cannot change the value of const variables by mistake :D So it's like a safety check.

Const can be used in many situations and places. Look at the following uses...

Const Pointer
The address of a constant pointer cannot be changed, but the value it points to, can be changed.
int * const p = &i;

Read it from right to left: p is a constant pointer to an int, which points to the address of i. Totally simple :P

Pointer to Const
What if we want to define a pointer to a constant int? Have Great attention:
const int * p = &i;

Again, read from right, p is a pointer to an int which is const. :rolleyes: Simple, right? but notice, there is another syntax for this, which is correct too:
int const * p = &i;

By reading from right to left we get: p is a pointer to a const int
It's the same as the one before functionally, so we can use both equally, use the one you are more comfortable with :)
The value p points to cannot be changed, but the address p points to Can be changed.

Const Pointer to Const
This is a mix of the previous two versions mentioned, have a look:
int const * const p = &i;

p is a constant pointer to a constant int, neither the value nor the address of p can be changed. :)

Pay extra attention: Const variables and pointers need assignment and definition at the Same time, otherwise you get a compilation error.

Const As Return
There are times that, you have to return a const reference/value in a function, sometimes they play an important role to avoid bugs:
char* func() {
	return "hey";
}

this function returns a pointer to a char array, actually returning a constant memory location, what happens if we write such code:
char * p = func();
p[0] = 'a';

This tries to change the value of a character in the array, but that memory location was constant and not meant for changing, which causes the program to crash with a nasty "Segmentation Fault" :rolleyes:
To solve this mistake and make it safe, use const like this:
const char* func() {
	return "hey";
}

Now, You cannot mistakenly change the value like before, as the pointer returned is a pointer to constant char :^: So you have to store this returned address in a pointer to const char, which disables any changes made to the value :P

Const As Argument
Constant objects come very handy as function arguments, it's like a promise to compiler that you Will Not change the value of that argument inside the scope of the function (or other cases, whichever you define).
The syntax is so simple and similar to what we had before:
void print(const int a) {
	cout<<a;
}

Here we didn't want to change a, just a simple print. Now that we defined the argument with const, we can have calls such as print(4) which we couldn't have without the const.

OK, were is the perfect use of this feature?... When passing by Reference! When you pass an object by reference to a function, you are allowed to directly change it's value, if we want to restrict the function and avoid any changes be made(and benefit passing by reference), we have to make this it const:
void print(const LargeType& a) {
	//do some stuff
}

Now, you are using the benefit of passing by reference and avoiding any changes made to the variable at the same time.
I am going to show you a class example with lots of const usage at the end... now we have 1 more section... :D

Const In Classes
By defining a member function as constant, you are banning that member function from making any changes to member variables. The syntax is as follows:
class foo {
	int val;
public:
	void const_member_func() const {
		cout<<val<<endl;
	}
};

Note the place of this const, this member function is banned from changing any member variables (here "val"). There are times when you Have to make a member function constant. Look at the following example:
class foo {
	int val;
public:
	const int& ret() {
		return val;
	}
	foo(const int& a) : val(a) {}
};

int main() {
	const foo f1(2); //the const makes a problem with the current class definition
	cout<<f1.ret()<<endl;
	return 0;
}

This code gives a compilation error. The reason is that, f1 is a constant foo. So the compiler has to make sure all members of the object remain unchanged, just change the class definition like this to correct the error:
class foo {
	int val;
public:
	const int& ret() const {
		return val;
	}
	foo(const int& a) : val(a) {}
};

int main() {
	const foo f1(2); //Now it doesn't have any problems
	cout<<f1.ret()<<endl;
	return 0;
}


OK... now I am going to write a sample class containing some useful usages of const:
#include <iostream>

using namespace std;

class foo {
	int val;
public:
	foo() {} //default constructor
	foo(const int& value) : val(value) {} //default constructor with initialization
	void operator=(const foo& right) { //operator= to assign data
		val = right.val;
	}
	const int& ret() const { //a function to return the private member, just for fun :D
		return val;
	}
	void set(const int& a) { //function for setting the member variable, operator= does this too
		val = a;
	}
	friend ostream& operator<<(ostream& o, const foo& right);
};

ostream& operator<<(ostream& o, const foo& right) {
	o<<right.val;
	return o;
}

int main () {
	foo f1(3);
	foo f2 = foo(2);
	cout<<f1<<" "<<f2<<endl;
	f1.set(57);
	f2 = f1;
	cout<<f1<<" "<<f2<<endl;
	return 0;
}

See? I used const a lot here... it's quite useful in most programs, you are just restricting yourself and avoiding any mistakes you may make by changing things when you don't want to.

Hope this tutorial could help you understand the usage of constants, as they are very useful! :D

Refer to [ Here ] for reference on const.

Is This A Good Question/Topic? 10
  • +

Replies To: Using Constant

#2 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Posted 19 March 2010 - 02:46 AM

Excellent tutorial.
Was This Post Helpful? 0
  • +
  • -

#3 PlasticineGuy  Icon User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Posted 06 April 2010 - 11:40 PM

I might add that const is a compile-time only feature and does not slow your program's run speed.
Also, note that it is mostly to prevent mistakes. You will be able to easily circumvent it if you try. For example:
class Foo {
    public:
        void Do(int x) const {
            Foo* pthis = const_cast<Foo*>(this);
            pthis -> bar = x;
        }
    private:
        int bar;
};
I just changed a member variable from within a const function that promised not to.

This post has been edited by PlasticineGuy: 06 April 2010 - 11:40 PM

Was This Post Helpful? 3
  • +
  • -

#4 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 311
  • View blog
  • Posts: 1,515
  • Joined: 16-May 09

Posted 10 April 2010 - 01:32 AM

Special Thanks to you for pointing this out :)
Was This Post Helpful? 0
  • +
  • -

#5 zero_cool1  Icon User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 32
  • Joined: 25-January 10

Posted 03 July 2010 - 06:40 PM

Quote

In C, there is #define with which you can define constant values, which is replaced by the preprocessor. This can benefit you when you want to use a value which is not meant to change at all... C++ has a feature to replace this usage of #define, it is called const


Firstly, very good tutorial man, thanks! And I guess this concept is also present in C language. So we've #define and const in C :online2long:
Was This Post Helpful? 0
  • +
  • -

#6 Banfa  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 83
  • View blog
  • Posts: 109
  • Joined: 07-June 10

Posted 04 July 2010 - 04:13 PM

View Postzero_cool1, on 04 July 2010 - 12:40 AM, said:

Firstly, very good tutorial man, thanks! And I guess this concept is also present in C language. So we've #define and const in C :online2long:
Well strictly you have #define in C++ as well sop both have both.

However consts in C are not as good as consts in C++, they are... how to put it... less constant. A constant in C++ is a true constant and can be used in most places a literal constant can be but a constant in C is just a variable that can not be changed, it can not be used anywhere that requires a literal constant.

As an example the following will compile in C++ but will not compile in C (C89 at least)

const int size = 5;

int main()
{
    int array[size];

    return 0;
}


Was This Post Helpful? 1
  • +
  • -

#7 C++ Programmer  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 20
  • View blog
  • Posts: 548
  • Joined: 12-June 08

Posted 04 July 2010 - 04:37 PM

Good job, very nice tutorial.
Was This Post Helpful? 0
  • +
  • -

#8 Xupicor  Icon User is offline

  • Nasal Demon
  • member icon

Reputation: 249
  • View blog
  • Posts: 582
  • Joined: 31-May 11

Posted 02 June 2011 - 08:23 AM

Very nice, although I find it strange that you omitted the usage of mutable when tackling const correctness. :) It'd be nice to add how mutable adds the "conceptual constness" to the bunch of terms. ;)
Was This Post Helpful? 0
  • +
  • -

#9 hulla  Icon User is offline

  • Writing Lines


Reputation: 49
  • View blog
  • Posts: 732
  • Joined: 05-March 11

Posted 05 September 2011 - 04:30 AM

Great tutorial. It was very helpful.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1