Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do programmers often use idioms like '40+1' instead of the actual number?

Tags:

c

coding-style

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.

like image 780
Richard Avatar asked Dec 08 '22 04:12

Richard


2 Answers

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.

like image 122
Dietrich Epp Avatar answered Jan 18 '23 14:01

Dietrich Epp


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.

like image 37
zubergu Avatar answered Jan 18 '23 14:01

zubergu