Welcome to our deep dive into C99 Designated Initializers! This tutorial is designed to guide both beginners and intermediates in understanding this powerful feature that was introduced in the C99 standard. 🎉
Designated Initializers allow you to initialize elements of an array, struct, or union with specific values, rather than initializing them in the order they appear. This can be particularly useful when you want to assign specific values to certain members, while leaving others uninitialized.
#include <stdio.h>
int main() {
int arr[4] = { [2] = 10, [0] = 5, [3] = 15 };
printf("Array elements:\n");
for(int i = 0; i < 4; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}In this example, we're initializing an array arr with 4 elements. We specifically assign the value 10 to the second index (arr[2]), 5 to the first (arr[0]), and 15 to the last (arr[3]).
#include <stdio.h>
typedef struct {
int id;
char name[20];
float salary;
} Employee;
int main() {
Employee emp = { .id = 1, .salary = 50000.50, .name = "John Doe" };
printf("Employee Details:\n");
printf("ID: %d\n", emp.id);
printf("Name: %s\n", emp.name);
printf("Salary: %.2f\n", emp.salary);
return 0;
}In this example, we're initializing a struct named Employee. We specifically assign the values for id, salary, and name.
What is the purpose of C99 Designated Initializers?
C99 Designated Initializers are a powerful tool for initializing arrays, structs, and unions in C. They provide flexibility, efficiency, and make your code more readable. We hope this tutorial has helped you understand this feature better. Happy coding! 🌟