Variables

Declarations & Definitions

To support seperate compilation, C++ distinguishes between declarations and definitions. A declaration makes a name known to the program. A file that wants to use a name defined elsewhere includes a declaration for that name. A definition creates the associated entity.

Differences between declarations & definitions

  • Declaration: Specify the type and name of a variable. Use extern keyword to distinguish declarations and definitions.
  • Definition: In addtion specify the type and name of a variable, it also allocates storage and initialize the variable.

Note 1: Any declaration that includes an explicit initializer is a definition. We can provide an initializer on a variable defined as extern, but doing so overrides the extern. An extern that has an initialier is a definition:

extern double pi = 3.1416;    // definition, overrides the extern

Note 2: Variables must be defined exactly once but can be declared many times.

Warning: It is an error to provide an initializer on an extern inside a function.

Identifiers

Identifiers in C++ can be composed of letters, digits, and the underscores character. No limitation on name length. Identifiers are case-sensitive. Identifiers must begin with either a letter or an underscore, but neither two consectuive unserscores nor an underscores followed immediately by an uppercase leeter is not allowed. In addtion, identifiers defined outside a function may not begin with an underscore.

Initializers

Initialization and assignment are different operations in C++, even though they use the same operator =, ande the distinction is irrelevant and can be ignored in other language.

Warning: Initialization is not assignment. Initilization happens when a variable is given a value when it is created. Assignment obliterates an object’s current value and replaces that value with a new one.

List Initialization

There are four different way to initialize an int type variable.

int x = 0;

int x = {0}; // list initialization

int x{0};    // list initialization

int x(0);

When used with variable of built-in type, this form of initialization has one important property: The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss of information.

long double ld = 3.1415926536;

int a{ld}, b = {ld}; // error: narrowing conversion required

int c(ld), d= ld;      // ok: but value will be truncated

Default Initialization

The value of built-in type that is not explicitly initialized depends on where it is defined. Variable defined outside any function are initialized to zero. With one exception, variables of build-in type defined inside a function are uninitialized, which is undefined instead. It is an error to copy or otherwise try to access the value of variable whose value is undefined.

发表评论

电子邮件地址不会被公开。 必填项已用*标注

15 − 10 =

85 − 81 =