Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't data instances NULL by default?

Something that has always bothered me is why isn't data set to NULL by the compiler, if nothing else was specified? I can't see any reason NOT to, and surely it must be better than the junk that gets referred to otherwise?

like image 361
KaiserJohaan Avatar asked Nov 21 '25 22:11

KaiserJohaan


2 Answers

The original reason was "for speed" -- the variables were only going to make sense once you assigned something to them, so there was an effort to not make a pointless initialization to 0 that was just going to be overwritten by the programmer in a few milliseconds with the actual data anyway.

While it isn't exactly expensive, compilers probably don't zero out variables today for the same reason: any compiler that does would look slow compared to other compilers on benchmarks.

like image 117
sarnold Avatar answered Nov 23 '25 11:11

sarnold


The only good reason is that it's not as efficient. C and C++ (unlike higher-level languages) tend not to do anything you didn't ask for. That is how they got the reputation of being extremely fast. Other languages are safer, but slower.

If you wanted to initialise fields to anything other than NULL, it would be a waste of time to first initialise it to NULL and then initialise it to whatever you set it to. So C/C++ assumes you know what you are doing.

like image 45
mgiuca Avatar answered Nov 23 '25 13:11

mgiuca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!