The main difference between const struct and struct in C lies in the mutability of variables. The const keyword restricts the content of variables from being modified after initialization.
When you declare a struct, it typically means you are creating a data structure whose members can be modified. When you add the const keyword before struct, it means that the structure and all its member variables cannot be modified after initialization.
Example:
Consider the following structure definition:
cstruct Person { char name[100]; int age; };
Example 1: Using struct
cstruct Person person1; strcpy(person1.name, "Alice"); person1.age = 30; // Modify the structure members strcpy(person1.name, "Bob"); person1.age = 25;
In this example, we declare a Person type variable person1 and are able to modify its member variables name and age after initialization.
Example 2: Using const struct
cconst struct Person person2 = {"Alice", 30}; // Attempt to modify structure members - this results in a compilation error // strcpy(person2.name, "Bob"); // Error! // person2.age = 25; // Error!
In this example, we declare a const struct Person type variable person2 and initialize it. Due to the const keyword, attempting to modify any member variables results in a compilation error.
Use Cases
Using const struct ensures data immutability, which is beneficial for scenarios requiring data security where modifications must be prevented, such as when passing large structures to functions without allowing modifications. This enhances code safety and maintainability.