Declaring an entity to be const tells the compiler to make it "read-only." const can be applied usefully in a large number of programming situations, as we will soon see.
Because it cannot be assigned to, a const object must be properly initialized. For example:
const int x = 33; const int v[] = {3, 6, x, 2 * x};
Working with the declarations above:
++x ; // error v[2] = 44; // error
Compilers can take advantage of an object being read-only in various ways. For integers and some simple types, no storage needs to be allocated for a const unless its address is taken. Therefore, most optimizing compilers try to store them in static memory.
It is good programming style to use const entities instead of embedding constant expressions (sometimes called "magic numbers") in your code. This will gain you flexibility later when you need to change the values and, in general, it will improve the maintainability of your programs. For example, instead of something like this:
for(i = 0; i < 327; ++i) { ... }
use something like this:
// const declaration section of your code const int SIZE = 327; ... for(i = 0; i < SIZE; ++i) { ... }
In some C/C++ programs, you might see constants defined with preprocessor macros like this: #define STRSIZE 80 [...] char str[STRSIZE]; Preprocessor macros get replaced before the compiler sees them. Using macros instead of constants means that the compiler cannot perform the same level of type checking as it can with proper constant expressions. Generally const expressions are preferred to macros for defining constant values in C++ programs. |
Part I: Introduction to C++ and Qt 4
C++ Introduction
Classes
Introduction to Qt
Lists
Functions
Inheritance and Polymorphism
Part II: Higher-Level Programming
Libraries
Introduction to Design Patterns
QObject
Generics and Containers
Qt GUI Widgets
Concurrency
Validation and Regular Expressions
Parsing XML
Meta Objects, Properties, and Reflective Programming
More Design Patterns
Models and Views
Qt SQL Classes
Part III: C++ Language Reference
Types and Expressions
Scope and Storage Class
Statements and Control Structures
Memory Access
Chapter Summary
Inheritance in Detail
Miscellaneous Topics
Part IV: Programming Assignments
MP3 Jukebox Assignments
Part V: Appendices
MP3 Jukebox Assignments
Bibliography
MP3 Jukebox Assignments