const

From Appmethod Topics
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

Modifiers

Syntax

const <variable name> [ = <value> ];
<function name> ( const <type>*<variable name> ;)
<function name> const;

Description

Use the const modifier to make a variable value unmodifiable.

Use the const modifier to assign an initial value to a variable that cannot be changed by the program. Any future assignments to a const result in a compiler error.

A const pointer cannot be modified, though the object to which it points can be changed. Consider the following examples.

const float pi   = 3.14;

// When used by itself, const is equivalent to int.
const  maxint  = 12345;

// A constant pointer
char *const str1 = "Hello, world";

// A pointer to a constant character string.
char const *str2 = "Appmethod C++";

Given these declarations, the following statements are illegal.

pi   = 3.0;         // Assigns a value to a const.
i     = maxint++;   // Increments a const.
str1 = "Hi, there!" // Points str1 to something else.

Using the const Keyword in C++ Programs

C++ extends const to include classes and member functions. In a C++ class definition, use the const modifier following a member function declaration. The member function is prevented from modifying any data in the class.

A class object defined with the const keyword attempts to use only member functions that are also defined with const. If you call a member function that is not defined as const, the compiler issues a warning that a non-const function is being called for a const object. Using the const keyword in this manner is a safety feature of C++.

Warning: A pointer can indirectly modify a const variable, as in the following:

*(int *)&my_age = 35;

If you use the const modifier with a pointer parameter in a function's parameter list, the function cannot modify the variable that the pointer points to. For example,

int printf (const char *format, ...);

printf is prevented from modifying the format string.

See Also