Initializers:
1. The initialized variable gets the value at the moment of Create: Double price = 109.99, Discount = Price * 0.6; Such a definition is reasonable.
Three ways of initialization:
1. int units = 0;
2. int units = {0};
3. int units{0};
4. Int units (0);
The 2nd and 3rd are list initialization, which has one feature: the initialization does not allow the possibility of loss information to occur (loss of information) such as:
Long double ld = 3.1415926;
int A{ld}, b = {ld}; //error:narrowing conversion required
int C (LD), d = ld; //ok:but value would be truncated
In the above initialization, the definition of A and B is wrong. 1. Double to int loses fractional parts, 2. int may not fit double.
Variable declarations and Definitions:
extern int i; //declares but does not define I
Int J; //declares and define J
extern int k = 3; //definition
extern is generally used to declare variables in other files, with extern when the variable type is added, and cannot be initialized.
Conventions for Variable Names (c + + variable naming convention):
1. An identifier should give some indication of its meaning.
2. Variable names normally is lowercase---index, not index or index.
3. Like Sales_item, classes we define usually begin with a uppercase letter
4. Identifiers with multiple words should visually distinguish each word, for example, Student_loan or Studentloan, not St Udentloan.
Scope of a Name:
#include <iostream>//to use a Globe variable and also define a local variable with the same nameint reused = 42;
//reused has Globe Scopeint Main () { int unique = 0;//unique have block scope //output#1:uses globe reused; PR INTs 0; Std::cout << reused << "<< unique << Std::endl; int reused = 0; New, local object named reused hides global reused //output#2:uses local reused; Prints 0 0 std::cout << Reused << "" << unique << Std::endl; output#3:explicitly requests the global reused; Prints 0 std::cout <<:: Reused << "" << unique << Std::endl; :: is a scope operator return 0;}
In the above code, a reused is defined both globally and locally, but does not specifically indicate the use of the global:: Reused words, using a local
When the same name is defined in the outer scope and inner scope within block scope, only the name within the inner scope can be used in the inner scope.
C++primer Learning Note (2)-variables (names initialization scope declare)