Initialization of Variables
Overview
Variables can be initialized during their definition.
Implicit initialization is not used; uninitialized variables hold arbitrary values.Initialization Rules by Scope
**Global and Static Variables:**
* Can only be initialized by a constant of the corresponding type or a constant expression.
* Initialization is performed only once.
**Local Variables:**
* Can be initialized by any expression, not just a constant.
* Initialization is performed every time the corresponding function is called.
Array and Structure Initialization
**General:**
* List of values must be enclosed in curly brackets
{}.
* Missed initializing sequences are considered equal to 0.
* The initializing sequence must have at least one value.
* If the array size is not specified, it is determined by the compiler based on the initialization sequence size.
**Multi-dimensional Arrays:**
* Cannot be initialized by a one-dimensional sequence (without additional curly brackets), unless only one initializing element is specified (typically zero).
**Arrays (including local):**
* Can only be initialized by constants.
**Structures:**
* Partial initialization is allowed.
* You can initialize one or more first elements; other elements will be initialized with zeroes.
Examples
**Simple Variables:**
int n = 1;
string s = "hello";
double f[] = { 0.0, 0.236, 0.382, 0.5, 0.618, 1.0 };
int a[4][4] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} };
int right[4]={WIDTH_IN_PIXELS+VERT_BORDER, WIDTH_IN_PIXELS+VERT_BORDER, WIDTH_IN_PIXELS+VERT_BORDER, WIDTH_IN_PIXELS+VERT_BORDER};
MqlTradeRequest request={0}; // Initializes all structure fields to zero
**Complex Structure Initialization:**
struct str3 { int low_part; int high_part; };
struct str10 { str3 s3; double d1[10]; int i3; }; // Example usage within a function:
// str10 s10_1={{1,0},{1.0,2.1,3.2,4.4,5.3,6.1,7.8,8.7,9.2,10.0},100};
// str10 s10_2={{1,0},{0},100}; // Initializes d1[0] to 0, rest to 0
// str10 s10_3={{1,0},{1.0},100}; // Initializes d1[0] to 1.0, rest to 0
Related Topics
[Data Types](/basis/types)
[Encapsulation and Extensibility of Types](/basis/oop/incapsulation)
[Visibility Scope and Lifetime of Variables](/basis/variables/variable_scope)
[Creating and Deleting Objects](/basis/variables/object_live)