Home > Backend Development > C++ > How are Automatic Structures and Arrays Partially Initialized in C and C ?

How are Automatic Structures and Arrays Partially Initialized in C and C ?

DDD
Release: 2024-12-19 05:32:21
Original
230 people have browsed it

How are Automatic Structures and Arrays Partially Initialized in C and C  ?

Partial Initialization of Automatic Structures and Arrays in C and C

The GNU C Reference Manual states that if a structure variable is not initialized, the values of its members are indeterminate. However, the standards do not define partial initialization of structures or arrays.

Partial Initialization Terminology

"Partial initialization" refers to providing some, but not all, initializers for an aggregate (array or structure).

Initialization Rules for Automatic Structures and Arrays

The C and C standards specify the following rules for initialization of automatic structures and arrays:

  • If the aggregate is completely initialized (i.e., there are enough initializers for all elements or members), the initialized elements/members are assigned the specified values, while the remaining elements/members are zero-initialized (for integral types) or NULL-initialized (for pointer types).
  • If the aggregate is not initialized, all elements/members are indeterminate.

Partial Initialization Behavior

Even though partial initialization is not explicitly defined in the standards, all mainstream compilers follow the following behavior:

  • For automatic arrays, if there are fewer initializers than the size of the array, the uninitialized elements are initialized to 0.
  • For automatic structures, if there are fewer initializers than the number of structure members, the uninitialized members are value-initialized. In C , this means that class data members are default-initialized, while non-class data members are zero-initialized.

Example

The following C code partially initializes a structure:

struct S {
    int a;
    char* b;
    int c;
};

S s = {1, "asdf"};
Copy after login

In this example, s.a is initialized to 1, s.b is initialized to "asdf", and s.c is zero-initialized because it is not explicitly initialized.

The above is the detailed content of How are Automatic Structures and Arrays Partially Initialized in C and C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template