Initialization of variables Initialization of variables Variable initialization

Initialization of variables

Initialization of variables • Variable initialization Initialize a variable in C to assign it a starting value. Without initialization the value will be garb Add an initialization to the declaration. Just tack on an assignment right to the end of the declaration • Syntax • data type variable=value; • int x = 5; • •

Initialization of variables • Array initialization • Array can initialize two ways • Array can be initialize put multiple comma-separated values inside curly brackets. • syntax: • data type array name [size]={value 1, value 2, value 3…. }; • eg • int month[12] = {31, 28, 31, 30, 31}; • The number of values between braces { } can not be larger than the size of array that we declare for the array between square brackets [ ].

Initialization of variables • Array initialization • Second method, you can leave off the array's size, and it will be filled in automatically: Syntax: • data type array name []={value 1, value 2, value 3…. }; • eg • int month[] = {31, 28, 31, 30, 31};

Initialization of variables • String initialization • Strings, which are really arrays of characters, also support a simpler format for initialization: Syntax: • data type array name [size]=“string”; • or • data type array name []=“string”; • eg • char name[10]=“ajith”; • char place[] = “kollam”;

Initialization of variables • Two-Dimensional Array initialization • Multidimensional arrays may be initialized by specifying bracketed values for each row. • Following is an array with 3 rows and each row has 3 columns. • int a[3][3]={{1, 1, 1}, {2, 2, 2}, {3, 3, 3}}; • then • a[0][0]=1 a[0][1]=1 a[0][2]=1 • a[1][0]=2 a[1][1]=2 a[1][2]=2 • a[2][0]=3 a[2][1]=3 a[2][2]=3

Initialization of variables • Pointer initialization • Declare a variable and not down the data type • Initialize the variable with some value • Declare a pointer variable of same data type, and assign the address of the first variable using the address operator (&) • int a=10, *p=&a;

Initialization of variables • Array pointer initialization • initialization in pointer format (since arrays are really pointers): • int *month = {31, 28, 31, 30, 31}; char *title = "My Program";

Initialization of variables • Structure initialization • • • structure members must be initialized in the order declared. A brace-enclosed single value. The initializer is preceded by an equal sign (=). Eg struct check { int a; float b; char name[20]; }; structure check k={10, 5. 3, ”ajith”};
- Slides: 9