Programming:C++/Const

From WhyAskWhy.org Wiki
Jump to: navigation, search


Does the const keyword precede or follow the data type?

You Can Do It!: A Beginners Introduction to Computer Programming

Francis Glassborow uses a form of initialization that he refers to as a function-style initialization, whereas I (and maybe you) are used to the assignment style for variables.

  • Page 37 shows const used after a data type in pseudocode: [1]
nothing climb_stairs(staircase const & stairs, person & me){
      for(int i(0); i != stairs.number_of_steps(); ++i){
                  me.step_up_one_step();
      }
}
  • Page 64 has (I added the comment):
// const is after the data type
string const endinput("END");
  • Appendix A mentions:
While there is some allowance for varying the position of const in a declaration, it must not come after the symbol that qualifies a type as a reference type.


C++ Primer Plus 5E

  • Pages 88-89 (comment by me):
// The const keyword is in front of the data type and variable
const int MONTHS = 12;

Does the const keyword precede or follow function declarations?

FIXME: Needs to be verified

It would seem that this is of use for pointers and references (not sure) as returning anything else would be a pass by value and const would not be needed.

To answer the question, it is a prefix for the return value.

Does the const keyword precede or follow member function declarations?

You Can Do It!: A Beginners Introduction to Computer Programming

  • Page 91:

const objects must have const member functions. The syntax for const member functions is to place the const keyword after the function parenthesis. This tells the compiler that any object passed to the function will not be changed.


References

  1. Fixed a typo here that is present in my edition of the book
 * [- Const Correctness]