Declaration

Use const variable declarations rather than C #define preprocessor to define symbolic constants because
"const" can be put before or after the type. const T and T const were always (both) allowed and equivalent. However, the first version will confuse fewer programmers ("is more idiomatic"). But these have different meaning in the pointer.
int *const p1 = q; // constant pointer to int variable
const int * p2 = q; // pointer to constant int
int const * p3 = q; // pointer to constant int

An object is declared volatile when its value can possibly be changed in ways outside either the control or detection of the compiler, for example, a variable updated by the system clock. The purpose is prevent to compiler aggressively optimizing code referring to the object.


Use size_t variable as size of arrays, strings or other data structure. Include <stdlib.h>, where it is defined as unsigned int (>=0). It is return type of sizeof operator and strlen() function.


A simple definition specifies the type and identifier of a variable. If the variable is defined at global scope, it is guaranteed to be provided with an initial value of zero. If the variable is defined at local scope or allocated dynamically through use of the new expression, it is uninitialized, or, its value is undefined. Literally, its associated memory contains a random bit pattern of the memory's previous use. The class mechanism provides automatic initialization of class objects through default constructor.
int i; // uninitialized local object
string s; // initialized with default string constructor

Because the use of an uninitialized object is a common program error and difficult to uncover, it is generally recommend that an initial value be provided for each defined object.


In C++ and C99, variable declarations (often declaration already be the definition, unless declare as extern) need not be congregated at the beginning of functions. Declaring variables close to the code where they are used and where they can be initialized with desired value is valuable because:

typedef char* cstring;
const cstring cstr; // not const char* cstr, but char *const cstr
The mistake is in conceptualizing typedef as a textual macro expansion. The const modifies the type of cstr, cstr is a pointer, therefore the definition declares cstr to be a constant pointer.

Index