C array initialization

For fewer initializers, refer to 4.9 Initialization in K&R and 6.7.8 Initialization in C99 standard.

 

 

#include <stdio.h>

// in bss section. static storage. initialized to 0
int global_array[10];

void global() {
	int i;

	printf("=== global ===\n");
	for (i = 0; i < 10; i++)
		printf("array[%d] = %d\n", i, global_array[i]);
}

void range() {
	int i;
	int array1[] = { [0 ... 1] = 10, [7 ... 9] = 8 };	
	printf("=== range ===\n");
	for (i = 0; i < 10; i++)
		printf("array[%d] = %d\n", i, array1[i]);
}

void no_initializers_for_array_on_stack() {
	int i;
	int array2[3];

	printf("=== no_initializers_for_array_on_stack ===\n");
	for (i = 0; i < 3; i++)
		printf("array2[%d] = %d\n", i, array2[i]);
}

void fewer_initializers() {
	int i;
	// Sames as int array2[] = { [0] = 1} };
	int array2[3] = {1}; // 

	printf("=== fewer_initializers ===\n");
	for (i = 0; i < 3; i++)
		printf("array2[%d] = %d\n", i, array2[i]);
}

int main(int argc, const char *argv[]) {
	global();
	no_initializers_for_array_on_stack();
	range();
	fewer_initializers();
	return 0;
}
 

你可能感兴趣的:(array)