Question:
Can I depend on an int being 0 after I declare it in c++?
Doug H
2014-12-21 18:50:15 UTC
When I first learned c++ more than 20 years ago, I found that after running the code:

int x;

You could pretty much depend on x NOT being 0. It would almost always have some other garbage value.

I've just gotten back into c++ lately, and found that the value IS 0 all of the times that I've tested it.
So it seems like compilers have changed this.

I'm still in the habit of not using a value before I assign it, but now I'm in a situation where I could be losing a lot of performance if I set the values after declaring the variables.

Specifically, something like this:

int x[300][300][300];

...in more than one object, being created regularly.

I'll be wasting a lot of CPU time if i go through this 3-dimensional array setting all those value to 0 if I don't need to.

So, with modern compilers, can I depend on those values all being 0 without having to set them all?
Three answers:
Ratchetr
2014-12-21 22:05:30 UTC
Careful here. The rules are complicated, and there are lots of cases where you can NOT depend on 0 initialization.



See first link for some of the rules. They get complicated.



See second link for an IDEOne hack I put together to try to illustrate things a bit (Yeah, it's not the best example. It's late).



One thing that HAS changed in the last 20 years is that operating systems are much more likely to 0 out memory before handing it off to a new application. You don't want rogue process A allocating a gig of memory and scanning it for patterns that look like a credit card swipe left in memory by point of sale application B.



That's why my IDEOne code deliberately fills some memory with -1, then frees it. (That isn't guaranteed to work, but it did here, so good enough for this demo).



As you can see from the example, ()'s make a big difference. f1 *pf1 = new f1; is very different from f1 *pf1 = new f1();

Adding your own constructors in the mix makes it more complicated. f2 has 2 constructors. One 0 initializes the array, the other doesn't.



You definitely need to be careful here. Know the rules, and minimize the chance of them being broken. And stress test. C++ will let you shoot your leg off if you aren't careful ;-)
?
2014-12-21 19:10:44 UTC
You can depend on your compiler initializing all ints to 0.

But if you plan to share your program, then you can't depend on every compiler to do the same.
Ab
2014-12-21 18:58:36 UTC
Yes you can


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...