Re:Initialization in C++ is bonkers (2017)
by jcelerier on Thursday May 15, 2025 @09:25PM
(#44000999)
int i;
does not initialize the value.
Re:Initialization in C++ is bonkers (2017)
by kstrauser on Thursday May 15, 2025 @09:47PM
(#44001112)
It's a gotcha to be sure. Sometimes it does, sometimes it doesn't. From a reference[0]:
#include <string>
struct T1 { int mem; };
struct T2
{
int mem;
T2() {} // “mem” is not in the initializer list
};
int n; // static non-class, a two-phase initialization is done:
// 1) zero-initialization initializes n to zero
// 2) default-initialization does nothing, leaving n being zero
int main()
{
[[maybe_unused]]
int n; // non-class, the value is indeterminate
std::string s; // class, calls default constructor, the value is ""
std::string a[2]; // array, default-initializes the elements, the value is {"", ""}
// int& r; // Error: a reference
// const int n; // Error: a const non-class
// const T1 t1; // Error: const class with implicit default constructor
[[maybe_unused]]
T1 t1; // class, calls implicit default constructor
const T2 t2; // const class, calls the user-provided default constructor
// t2.mem is default-initialized
}
That `int n;` on the 11th line is initialized to 0 per standard. `int n;` on line 18, inside a function, is not. And `struct T1 { int mem; };` on line 3 will have `mem` initialized to 0 if `T1` is instantiated like `T1 t1{};`, but not if it's instantiated like `T1 t1;`. There's no way to tell from looking at `struct T1{...}` how the members will be initialized without knowing how they'll be called.C++ is fun!
[0]https://en.cppreference.com/w/cpp/language/default_initializ...
Stroustrup once said
> "There's a great language somewhere deep inside of C++"
or something to that effect.
Yes, it's called Simula-67.
(the original pre-ISO C++ is basically C with Simula bolted onto it.)
Re:Initialization in C++ is bonkers (2017)
by portaltonowhere on Thursday May 15, 2025 @09:57PM
(#44001178)
Unless `i` is global…
Re:Initialization in C++ is bonkers (2017)
by waynecochran on Friday May 16, 2025 @12:35AM
(#44001870)
Most cases, e.g. local var declaration. `int i` does not initialize i.
So, do you?