On 2020-08-03, Rainer Weikusat <
rwei...@talktalk.net> wrote:
> Kaz Kylheku <
793-84...@kylheku.com> writes:
>> On 2020-08-03, G G <
gdo...@gmail.com> wrote:
>>> /* open the shared memory object */
>>> fd = shm_open( name, O_RDONLY, 0666);
>>
>> Where is the test for the success of this operation?
>>
>> Also, as a mattery of style, consider avoiding assignments, wherever
>> possible, in favor of initializations:
>>
>> int fd = shm_open(...)
>> char *ptr = (char *) mmap ...
>
> As a matter of style, I argue for the opposite: Don't declare a new
> variable whenever you happen to believe you need one. Code which declares
If a variable is calculated once and consumed only in one place, and the
expression which calculates is short and understadable, it makes sense
to eliminate the variable and just use the expression in its place.
However, that is not advisable unless you're sure that there are no
important side effects being reordered.
int ch = getchar();
int res = foo(fun_with_effect(), ch);
Here we know that getchar is called first, then fun_with_effect.
Not so if we eliminate the variable:
int res = foo(fun_with_effect(), getchar());
Variables give intermediate results names, which can clarify things.
> a variable named i fifteen times because nobody could be arsed to check
> if a variable i was already declared contains a lot of redundant text
> and texts with lots of (pointless) repetitions are difficult to read and
> understand.
Declaring a separate dummy variable i in a block of code like this
{ /* C89 */
int i;
for (i = 0; ....) {
}
}
is actually a good idea. It follows the idea of minimal scope. An
identifier is introduced just before it is needed, and its scope ends
at the soonest point where it is no longer needed.
We know that any mention of any i elsewhere outside of this block is
referring to some other i.
It also illustrates why mixed declarations and statements are such a
misfeature:
type x = blah();
statement(x);
statement;
type y = foo();
// X has no "next use" any more, yet is still in scope.
statement(y);
Nested scopes should always have and *end* that is as short as possible,
not only a start. Above it is clear that x and y are declared close
to where they are needed; but then they linger way past no longer being
needed. You want:
{
type x = blah();
statement(x);
statement;
// X has no "next use" any more; consequently we cut off
// the scope here.
}
{
type y = foo();
statement(y);
}
It is so helpful to the reader to know where *not* to look for
interactions with a variable.