Monday, January 26, 2009

Initialization of Variables in C Program

An external variable may be initialized at compile time by following its name with an initializing value when it is defined. The initializing value has to be something whose value is known at compile time, like a constant.
int x 0; /* "0" could be any constant */
int a 'a';
char flag 0177;
int *p &y[1]; /* p now points to y[1] */
An external array can be initialized by following its name with a list of initializations enclosed in braces:
int x[4] {0,1,2,3}; /* makes x[i] = i */
int y[ ] {0,1,2,3}; /* makes y big enough for 4 values */
char *msg "syntax error\n"; /* braces unnecessary here */
char *keyword[ ]{
"if",
"else",
"for",
"while",
"break",
"continue",
0
};
This last one is very useful -- it makes keyword an array of pointers to character strings, with a zero at the end so we can identify the last element easily. A simple lookup routine could scan this until it either finds a match or encounters a zero keyword pointer:
lookup(str) /* search for str in keyword[ ] */
char *str; {
int i,j,r;
for( i=0; keyword[i] != 0; i++) {
for( j=0; (r=keyword[i][j]) == str[j] && r != '\0'; j++ );
if( r == str[j] )
return(i);
}
return(-1);
}

No comments:

Post a Comment