I've stumbled across the following code snippet I found:
char firstname[40+1];
char lastname[40+1];
Why did the person not just use 41 as the array length? And why did he use an odd number like 41 anyway?
I can't present any examples now, but I've seen this pattern a couple of times already and never understood what the point of it was.
Same reason that we do things like this:
double normal_pdf(double x) {
return (1.0 / sqrt(2.0 * pi)) * exp(x * x / 2.0);
// or even...
return (1.0 / sqrt(8.0 * atan(1.0)) * exp(x * x / 2.0);
}
Instead of...
double normal_pdf(double x) {
return 0.3989422804014327 * exp(x * x * 0.5);
}
The two versions will produce the same machine code, with a decent optimizing compiler, but the first version is obviously correct while the second version could be wrong--or at least it takes longer for a human reader to verify that the code is correct.
I suspect that in the case of char field[40+1]
, the +1
is there to hold a NUL terminator, and the field has a maximum length of 40 characters.
Just to remind you or anyone else reading/modifying this code that the actual char array has size of x. Plus 1 for the null terminator.
In C things go wrong so fast that anything that improves readibility is worth its time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With