[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CConst

(C) const

Keyword being an abbreviation of 'constant'. Use const whenever possible.

int main()
{
  const int x = 69;
  return 0;
}


In functions const can be used to indicate a 'read-only' from  ?struct

typedef struct
{
  int mX;
} MyStruct;
/* Most common */
void transmogrify1(const MyStruct * pMyStruct)
{
  /* pMyStruct->mX = 12; Error: cannot modify where pMyStruct points to */
  pMyStruct = 0; /* Okay, won't do harm to pMyStruct */
}
/* Most uncommon */
void transmogrify2(MyStruct * const pMyStruct)
{
  pMyStruct->mX = 12; /* Okay, can modify where pMyStruct points to */
  /* pMyStruct = 0;      Error: cannot modify where pMyStruct points to */
}
/* Common */
void transmogrify3(const MyStruct * const pMyStruct)
{
  /* pMyStruct->mX = 12; Error: cannot modify where pMyStruct points to */
  /* pMyStruct = 0;      Error: cannot modify where pMyStruct points to */
}


To indicate that MyStruct is only read from, use transmogrify1 and transmogrify3. To save typing, many choose transmogrify1.

'const' links



last edited (November 11, 2006) by bilderbikkel, Number of views: 1678, Current Rev: 4 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.