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

I came across the following piece of code that I found:

char firstname[40+1];
char lastname[40+1];

Why didn't people just use 41 as the length of the array? And why did he use an odd number, like 41?

Now I can’t imagine any examples, but I saw this template a couple of times and never understood what it was.

+4
source share
3 answers

For the same reason that we do such things:

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...

double normal_pdf(double x) {
    return 0.3989422804014327 * exp(x * x * 0.5);
}

, , , , - , , , , .

, char field[40+1], +1 NUL-, 40 .

+7

- / , char x. 1 .

C , , , .

+5
char firstname[40+1];

40 + 1used to make it explicit, an array can contain a string of length 40, but with a byte 1reserved for the null terminator. A length string Nhas the size of N + 1bytes (i.e. a sizeofstring object N + 1). It is used for documentation purposes.

+2
source

All Articles