Home > Backend Development > C++ > How Can I Properly Initialize Static Members in C ?

How Can I Properly Initialize Static Members in C ?

Barbara Streisand
Release: 2024-12-14 05:51:10
Original
189 people have browsed it

How Can I Properly Initialize Static Members in C  ?

Static Member Initialization in C

In C , defining static members within class definitions can be a confusing topic. This article addresses questions regarding the initialization of static variables in C , exploring why in-class initialization is forbidden and how to properly initialize them.

1. Prohibition of In-Class Initialization

When attempting to define a public static variable within a class declaration, as shown below, compilation errors may occur:

public:
static int j = 0;
Copy after login

This is because the C standard prohibits the initialization of non-const static members within class declarations, as stated in the error message: "ISO C forbids in-class initialization of non-const static member 'j'."

2. Permissible Initialization of Const Members

In contrast to non-const static members, const static members can be initialized within class declarations. This is allowed because const members are considered compile-time constants and must be initialized with a value that is known at compile time.

3. Initialization of Static Variables in C

In C , static variables are not automatically initialized to zero as they are in C. To initialize static variables in C , you must explicitly define their initial values outside of the class declaration, typically in a separate source file (.cpp).

For example, to initialize the static variable j declared above, you would modify the code as follows:

// Header file
class Test {
public:
    static int j;
};

// Source file
int Test::j = 0;
Copy after login

Conclusion

In C , in-class initialization of non-const static members is forbidden due to the need for flexibility in initializing static variables outside of class declarations. Const static members, however, can be initialized in class declarations. Static variables are not automatically initialized to zero in C ; their initial values must be explicitly defined.

The above is the detailed content of How Can I Properly Initialize Static Members in 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template