[C + +] CONST 2

Source: Internet
Author: User

The C + + ' const ' declaration:why & How

The ' const ' system is one of the really messy features of C + +.

It is simple in concept:variables declared with ' const ' added become constants and cannot are altered by the program. However it is also used to bodge in a substitute for one of the missing features of C + + and there it gets horridly complic Ated and sometimes frustratingly restrictive. The following attempts to explain how ' const ' are used and why it exists.

Simple use of ' const '

The simplest use are to declare a named constant. This is available in the ancestor of C + +, C.

To does this, one declares a constant as if it is a variable but add ' const ' before it. One have to initialise it immediately in the constructor because, of course, one cannot set the value later as that would b e altering it. For example,

const int Constant1=96;

Would create an integer constant, unimaginatively called " Constant1 , with the value 96.

Such constants is useful for parameters which is used in the program but is do not need-be changed after the program is compiled. It has a advantage for programmers over the C preprocessor " #define command in that it's understood & used by the COM Piler itself, not just substituted to the program text by the preprocessor before reaching the main compiler, so error m Essages is much more helpful.

It also works with pointers but one have to be careful where's const’ put as that determines whether the pointer or what I T points to is constant. For example,

const int * Constant2

Declares Constant2 A variable pointer to a constant integer and

int const * Constant2

is an alternative syntax which does the same, whereas

int * const Constant3

Declares that's Constant3 constant pointer to a variable integer and

int const * const Constant4

Declares that Constant4 was constant pointer to a constant integer. Basically ' const ' applies to whatever are on its immediate left (other than if there are nothing there in which case it APPL IES to whatever is it immediate right).

Use of the ' const ' in Functions Return Values

Of the possible combinations of pointers and " const , the constant pointer to a variable are useful for storage that can B E changed in value and not moved in memory.

Even more useful are a pointer (constant or otherwise) to a ' const value. This was useful for returning constant strings and arrays from functions which, because they was implemented as pointers, T He program could otherwise a try to alter and crash. Instead of a difficult to track down crash, the attempt to alter unalterable values would be detected during compilation.

For example, if a function which returns a fixed ' Some text ' string was written like

char *Function1()
{ return “Some text”;}

Then the program could crash if it accidentally tried to alter the value doing

Function1()[1]=’a’;

Whereas the compiler would have spotted the error if the original function had been written

const char *Function1()
{ return "Some text";}

Because the compiler would then know, the value was unalterable. (Of course, the compiler could theoretically has worked that off anyway but C was not that clever.)

Where it Gets messy-in Parameter passing

When a subroutine or function was called with parameters, variables passed as the parameters might was read from in order to Transfer data into the Subroutine/function, written to on order to transfer data back to the calling program or both to D o both. Some languages enable one to specify this directly, such as has ' in: , ' out: & ' inout: parameter types, whereas In C one have to work at a lower level and specify the method for passing the variables choosing one that also allows the Desired data transfer direction.

For example, a subroutine like

void Subroutine1(int Parameter1)
{ printf("%d",Parameter1);}

Accepts the parameter passed to it in the default C & C + + Way-which is a copy. Therefore The subroutine can read the value of the variable passed to it and not alter it because any alterations it makes is only made to the copy and is lost when the subroutine ends. e.g.

void Subroutine2(int Parameter1)
{ Parameter1=96;}

Would leave the variable it is called with unchanged not set to 96.

The addition of an "to the & parameter name in C + + (which is a very confusing choice of symbol because an" in & Front of variables elsewhere in C generates pointers!) Causes the actual variable itself, rather than a copy, to is used as the parameter in the subroutine and therefore can is Written to thereby passing data back out the subroutine. Therefore

void Subroutine3(int &Parameter1) 
{ Parameter1=96;}

Would set the variable it is called with to 96. This method of passing a variable as itself rather than a copy are called a ' reference ' in C + +.

That's the passing variables was a C + + addition to C. To pass an alterable variable in original C, a rather involved method was used. This involved using a pointer to the variable as the parameter then altering what it pointed to is used. For example

void Subroutine4(int *Parameter1) 
{ *Parameter1=96;}

Works but requires the every use of the variable in the called routine altered like that and the calling routine also Alte Red to pass a pointer to the variable. It is rather cumbersome.

But where does " const come into this? Well, there are a second common use for passing data by reference or pointer instead of as a copy. That's when copying the variable would waste too much memory or take too long. This is particularly likely with large & compound user-defined variable types (' structures ' in C & ' classes ' in c+ +). So a subroutine declared

void Subroutine4(big_structure_type &Parameter1);

Might being using ' & because it is going to alter the variable passed to it or it might just being to save copying time And there is no-which it is if the function was compiled in someone else ' s library. This could is a risk if one needs to the trust of the subroutine not to alter the variable.

To solve this, " const can be used in the parameter list. e.g.

void Subroutine4(big_structure_type const &Parameter1);

Which would cause the variable to being passed without copying but stop it from then being altered. This is messy because it's essentially making an in-only variable passing method from a Both-ways variable passing method Which was itself made from a in-only variable passing method just to trick the compiler into doing some optimization.

Ideally, the programmer should not need control this detail of specifying exactly how it variables is passed, just say wh Ich direction the information goes and leave the compiler to optimize it automatically, but C is designed for raw Low-lev El programming on powerful computers than is standard these days so the programmer have to do it explicitly.

Messier still-in the Object oriented programming

In object oriented programming, calling a ' method ' (the object oriented name is a function) of an object gives an extra C Omplication. As well as the variables in the parameter list, the method had access to the member variables of the object itself which a Re always passed directly not as copies. For example a trivial class, " Class1 , defined as

class Class1
{ void Method1();
  int MemberVariable1;}

Have no explicit parameters at all to "but calling it in an object in this Method1 class might alter" of that MemberVariable1 object If ' Method1 happened to is, for example,

void Class1::Method1()
{ MemberVariable1=MemberVariable1+1;}

The solution to that's to put "after the const parameter list like

class Class2
{ void Method1() const;
  int MemberVariable1;}

Which would ban in from Method1 Class2 being anything which can attempt to alter any member variables in the object.

Of course one sometimes needs to combine some of the these different uses of ' const which can get confusing as in

const int*const Method3(const int*const&)const;

Where the 5 uses ' const respectively mean that the variable pointed to by the returned pointer & the returned pointer itself won ' t is alterable and that the method does not alter the variable pointed to by the given pointer, the given Poin TER itself & the object of which it is a method!.

Inconveniences of ' const '

Besides const the confusingness of the ' syntax, there is some useful things which the system prevents programs doing.

One in particular annoys me because my programs often needed to being optimized for speed. This is the A method which is declared 'const' cannot even make changes to the hidden parts of it object that would do any changes that would being apparent from T He outside. This includes storing intermediary results a long calculations which would save processing time in subsequent calls to th E class ' s methods. Instead it either have to pass such intermediary results back to the calling routine to store and pass back next time (mess Y) or recalculate from scratch next time (inefficient). In later versions of C + +, the 'mutable' keyword was added which enables 'const' To is overridden for this purpose but it totally relies on trusting the programmer to only use it for that purpose so, I f you has to write a program using someone else ' s class which uses 'mutable' Then you cannot guarantee that 'mutable' Things'll really be constant which renders 'const' Virtually useless.

One cannot simply avoid using 'const' On class methods because 'const' Is infectious. An object which have been made 'const', for example by being passed as a parameter in the 'const &' The can only has those of its methods that is explicitly declared 'const' Called (because C + + ' s calling system is too-simple-to-work-out which methods not explicitly declared 'const' Don ' t actually change anything. Therefore class methods that don ' t change the object is best declared 'const' So ' they is not prevented from being called when a object of the class has somehow acquired 'const' Status. In later versions of C + +, an object or variable which have been declared 'const' can be converted-changeable by use of 'const_cast' Which is a similar bodge to 'mutable' and using it likewise renders 'const' Virtually useless.

by Andrew Hardwick.
Distributable under GPL freeware licence.
Written 2001.
Converted to HTML & augmented 2002/3/13.
Updated 2002/8/9, 2004/7/19, 2005/6/9 & 2006/5/22.
Spelling corrections 2008/3/4.
Grammar Corrections & Clarifications 2011/6/16.
Typo correction 2011/12/29.
Typo Corrections 2012/4/4.
Available on-line at http://duramecho.com.

[C + +] CONST 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.