Home > Backend Development > C++ > Why Can't I Initialize Static Members and Arrays Directly in a C Class?

Why Can't I Initialize Static Members and Arrays Directly in a C Class?

Linda Hamilton
Release: 2024-12-08 06:08:11
Original
737 people have browsed it

Why Can't I Initialize Static Members and Arrays Directly in a C   Class?

Why I Can't Initialize Non-Const Static Member or Static Arrays in a Class?

In C , static data members in a class cannot be initialized directly within the class definition, except for certain specific cases.

Reason for Restricting Non-Const Static Member Initialization

Static data members are allocated in the memory segment of the program and are shared among all instances of the class. The C standard forbids their in-class initialization to prevent multiple definitions of the same variable in multiple translation units.

Reason for Restricting Static Array Initialization

Similarly, static arrays in a class cannot be initialized in-class because arrays occupy a contiguous block of memory. Allowing in-class initialization would lead to multiple copies of the same array being created in each translation unit, resulting in unexpected behavior.

Exception for Const Integral and Enum Types

An exception to these rules is made for static const integral types and enumeration types. These types can be initialized in-class because they are treated as compile-time constants and their values are known at the moment of compilation.

Workaround for Array Initialization

To initialize a static array in a class, you can use the "enum trick":

enum { arrsize = 2 };
static const int c[arrsize] = { 1, 2 };

This approach declares an enumeration constant arrsize to determine the array size, which is then used to initialize the static const array c.

Evolution in C 11

C 11 has relaxed these restrictions somewhat. Now, static data members of certain types, known as "literal types," can be initialized in-class using a brace-or-equal-initializer. Additionally, C 11 allows non-static data members to be initialized in-class using constant expressions.

The above is the detailed content of Why Can't I Initialize Static Members and Arrays Directly in a C Class?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template