- C++ programmers tend to refer to variables as “variables” or “objects” interchangeably.
- Most generally, an object is a region of memory that can contain data and has a type.
Variable Definitions
type specifier with identifiers and initializers
a declaration is a base type followed by a list of declarators.
Initialization is not assignment. Initialization 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
vector<int> ivec2(ivec); // copy
vector<int> ivec3 = ivec; // copy
vector<int> ivec4(10, 1); // construct
vector<int> ivec5(10); // construct
vector<string> art = {“a”, “ab”}; // list init
vector<string> art2{“a”, “ab”}; // list init
vector<string> art3(“a”, “ab”); // error
vector<string> art5{10, “hi”}; // construct
圆括号不是list init,是construct。当它收到variable,会copy;当它收到int literal,会多份。这完全取决于类中是怎么定义的。
而花括号,通常是新标准下的list init,只有当can’t make sense,它会自己转变为construct。
可是我好端端的干嘛搞这么复杂
这么多个例子只是为了对照,不为了记忆。
Default Initialization
What that default value is depends on the type of the variable and may also depend on where the variable is defined.
Type like “class” control how we initialize objects of that class type. Like “reference”, dosen’t allow no initialization, and “string” class give empty string literal when not be initialized.
Some built-in type with no initialization have a undefined value. undefined mean different from compilers.
Variable Declarations and Definitions
- A declaration makes a name known to the program
- A variable definition is a declaration. In addition to specifying the name and type, a definition also allocates storage and may provide the variable with an initial value.
- Variables must be defined exactly once but can be declared many times.
Use in Other File
declare with extern
but no initializers, otherwise it is a definition.
for const
, because the scope is the whole file, we use the keyword extern on both its definition and declaration(s)
Scope
A scope is a part of the program in which a name has a particular meaning.
Most scopes in C++ are delimited by curly braces (block scope).
Nested Scopes
- inner scope can use the name declared in the outer scope.
- redeclare in inner scope can hide the name have declare in the outer scope.
- to fetch the global variable➡️^a798ff
terms | means |
---|---|
initializers | Let the object get the specified value. |
identifiers | the name of the variable |
base type | when int* , the base type is int |
declarators | include type modifiers and identifiers |