C++ Variable Initialization

Discussions focus on the rules, pitfalls, and safety issues of default and zero-initialization for variables and structs in C++, comparisons to Rust's stricter model, and proposals for improvements like explicit uninitialized markers in future standards.

➡️ Stable 0.9x Programming Languages
2,179
Comments
19
Years Active
5
Top Authors
#4825
Topic ID

Activity Over Time

2008
4
2009
5
2010
15
2011
33
2012
38
2013
79
2014
98
2015
101
2016
133
2017
123
2018
126
2019
189
2020
122
2021
130
2022
232
2023
189
2024
184
2025
360
2026
18

Keywords

e.g cppguide.x std.org C99 NULL L119 HandleTheFoo www.open i.e stackoverflow.com foo struct int compiler constructor zero variable std language value

Sample Comments

MonkeyClub May 12, 2022 View on HN

Good question! I'm not entirely sure, perhaps it's defense against the compiler optimizing the initialization out?

ncruces Oct 1, 2025 View on HN

Rust mandates that every field in a user-defined type is initialized at once. How do you propose to retrofit that into C without "constructors"?

chris_wot Nov 29, 2022 View on HN

constinit allows for constant initialization. Why, how enlightening! Now... what is constant initialization?

ryandrake May 16, 2025 View on HN

Ideally, there would be a keyword for it. So ‘A a;’ would not compile. You’d need to do ‘A a{};’ or something like ‘noinit A a;’ to tell the compiler you’re sure you know what you are doing!

zabzonk Mar 20, 2024 View on HN

i said "if a type has a constructor". but if you are fiddling around with ints and chars and the like, then you will need to initialise them. i have been writing c++ since the mid80s and have never found this to be a problem, or at least no more than it would be to use an uninitialised int variable in C.

Tomis02 May 7, 2022 View on HN

I think that was the author's point. You _can_ use them this way but it's a hassle and most people don't do it. The language itself doesn't protect you against zero-initialisation errors, even though it could.

akoboldfrying Apr 26, 2025 View on HN

Initialisation in C++ is just footguns all the way down.

tekknik Jul 26, 2022 View on HN

that’s just a choice by the language designer. nothing prohibits initialization at runtime.

saagarjha Aug 2, 2021 View on HN

I suspect that to many C++ programmers, most initializations of structs have unpredictable side effects because of how complex they are ;)

WalterBright Jan 6, 2026 View on HN

You're the first who has told me he doesn't like default initialization!