乐闻世界logo
搜索文章和话题

How does a 'const struct' differ from a ' struct '?

1个答案

1

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:

c
struct Person { char name[100]; int age; };

Example 1: Using struct

c
struct 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

c
const 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.

2024年6月29日 12:07 回复

你的答案